Reputation:
I am making software that will need to dynamically create java bytecode, and possibly even make it a runnable jar.
My current idea is to create a new .java file and compile it at runtime. I can create the file, but I'm not sure how to compile it at runtime, and make it a runnable jar. Any help would be greatly appreciated.
public static String generate(String filePath) {
try {
File file = new File("Test.java");
if(!file.exists())file.createNewFile();
FileWriter write = new FileWriter(filePath+".java");
BufferedWriter out = new BufferedWriter(write);
out.write(
"public class Test {\n\t" +
"public static void main(String[] args){\n\t\t"+
"System.out.println(\"Working\");\n\t"+
"}\n" +
"}"
);
out.close();
} catch (Exception e) {// Catch exception if any
return "Error: " + e.getMessage();
}
return "Test.java created!";
}
Upvotes: 0
Views: 2550
Reputation: 11815
You can certainly use ASM and the like, but don't discount scripting languages on the jvm. ASM might be confusing if you're not very familiar with the vm and bytecode in general. You could generate groovy or jython (or whatever language you like) code to a file, and package that up with a main program in a jar file.
As an example, you create a main program which looks for a classpath resource and sends it off to the groovy scripting language:
Binding binding = new Binding();
// maybe set some binding variables here
GroovyShell shell = new GroovyShell(binding);
GroovyCodeSource source =
new GroovyCodeSource(
Thread.currentThread().getContextClassLoader().getResource("script.groovy"));
Object value = shell.evaluate(source);
Once you have that, it would be easy to package up the main class and the script in an executable jar. You could even unpack the groovy-all.jar and pack it up in your jar to make it a fully self contained executable jar file.
It all boils down to what you are trying to accomplish, and either approach would probably work for you.
Upvotes: 1
Reputation: 328800
To compile Java code, you can use the Java Compiler API.
To generate byte code directly, you can use tools like ASM.
To generate an executable JAR, create a JarOutputStream with a manifest that declares the main class.
Upvotes: 7