• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

OpenHFT/Java-Runtime-Compiler: Java Runtime Compiler

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

OpenHFT/Java-Runtime-Compiler

开源软件地址:

https://github.com/OpenHFT/Java-Runtime-Compiler

开源编程语言:

Java 100.0%

开源软件介绍:

Chronicle Runtime Compiler

badge javadoc GitHub release%20notes subscribe brightgreen measure?project=OpenHFT Java Runtime Compiler&metric=alert status

This takes a String, compiles it and loads it returning you a class from what you built. By default it uses the current ClassLoader. It supports nested classes, otherwise builds one class at a time.

On Maven Central

You can include in your project with

<dependency>
    <groupId>net.openhft</groupId>
    <artifactId>compiler</artifactId>
    <version><!-- The latest version (see above) --></version>
</dependency>

Simple example

You need a CachedCompiler and access to your JDK’s tools.jar.

// dynamically you can call
String className = "mypackage.MyClass";
String javaCode = "package mypackage;\n" +
                 "public class MyClass implements Runnable {\n" +
                 "    public void run() {\n" +
                 "        System.out.println(\"Hello World\");\n" +
                 "    }\n" +
                 "}\n";
Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
Runnable runner = (Runnable) aClass.newInstance();
runner.run();

I suggest making your class implement a KnownInterface of your choice as this will allow you to call/manipulate instances of you generated class.

Another more hacky way is to use this to override a class, provided it hasn’t been loaded already. This means you can redefine an existing class and provide the methods and fields used match, you have compiler redefine a class and code already compiled to use the class will still work.

Using the CachedCompiler.

In this example, you can configure the compiler to write the files to a specific directory when you are in debug mode.

private static final CachedCompiler JCC = CompilerUtils.DEBUGGING ?
                                                   new CachedCompiler(new File(parent, "src/test/java"), new File(parent, "target/compiled")) :
                                                   CompilerUtils.CACHED_COMPILER;

By selecting the src directory to match where your IDE looks for those files, it will allow your debugger to set into the code you have generated at runtime.

Note: you may need to delete these files if you want to regenerate them.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap