0

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!";
}
1
  • 1
    If you create the byte code in memory you can load it directly into your ClassLoader without having to write any files. Commented Aug 3, 2012 at 10:08

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I ended up creating the java file, compiling it, then building a jar. Thanks again!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.