Add the compiler Maven dependency
masterTo use this library, add the following dependency to your pom.xml file:
<dependency>
<groupId>com.itranswarp</groupId>
<artifactId>compiler</artifactId>
<version>1.0</version>
</dependency>repository·master·Indexed 18 days ago
https://github.com/michaelliao/compilerA utility for compiling Java source code in memory using the Java 6 compiler API. It provides the JavaStringCompiler class to compile source strings and load resulting classes on-the-fly without writing files to disk, serving as a lightweight alternative to CGLIB or Javassist for proxy generation.
To use this library, add the following dependency to your pom.xml file:
<dependency>
<groupId>com.itranswarp</groupId>
<artifactId>compiler</artifactId>
<version>1.0</version>
</dependency>You can use JavaStringCompiler to compile Java source code provided as a String and load the resulting classes on-the-fly without writing files to disk. This is useful for generating proxy classes or executing dynamically generated code.
JavaStringCompiler.compile(String fileName, String sourceCode) to get a Map<String, byte[]> containing the class names and their corresponding bytecode.loadClass(String className, Map<String, byte[]> results) to load the class into the JVM.newInstance()) to create an instance of the loaded class.public class Main {
public static void main(String[] args) {
JavaStringCompiler compiler = new JavaStringCompiler();
Map<String, byte[]> results = compiler.compile("UserProxy.java", JAVA_SOURCE_CODE);
Class<?> clazz = compiler.loadClass("on.the.fly.UserProxy", results);
// try instance:
User user = (User) clazz.newInstance();
}
static final String JAVA_SOURCE_CODE = "/* a single java source file */ "
+ "package on.the.fly; "
+ "public class UserProxy extends test.User { "
+ " boolean _dirty = false; "
+ " public void setId(String id) { "
+ " super.setId(id); "
+ " setDirty(true); "
+ " } "
+ " public void setName(String name) { "
+ " super.setName(name); "
+ " setDirty(true); "
+ " } "
+ " public void setCreated(long created) { "
+ " super.setCreated(created); "
+ " setDirty(true); "
+ " } "
+ " public void setDirty(boolean dirty) { "
+ " super.setDirty(dirty); "
+ " } "
+ " public boolean isDirty() { "
+ " return this._dirty; "
+ " } "
+ "} ";
}