Skip to content

Latest commit

History

315 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Chronicle Runtime Compiler

badgejavadocGitHubrelease%20notes subscribe brightgreenmeasure?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 callStringclassName = "mypackage.MyClass";
StringjavaCode = "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);
Runnablerunner = (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.

privatestaticfinalCachedCompilerJCC = CompilerUtils.DEBUGGING ?
newCachedCompiler(newFile(parent, "src/test/java"), newFile(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.

About

Java Runtime Compiler

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages