动态创建Java字节码和可运行的jar [英] Dynamically create java bytecode and runnable jar

查看:165
本文介绍了动态创建Java字节码和可运行的jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作需要动态创建Java字节码,甚至可能使其成为可运行jar的软件。

I am making software that will need to dynamically create java bytecode, and possibly even make it a runnable jar.

我目前的想法是创建一个新的.java文件并在运行时进行编译。我可以创建文件,但不确定如何在运行时进行编译,并使其成为可运行的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!";
}


推荐答案

要编译Java代码,您可以使用 Java编译器API

To compile Java code, you can use the Java Compiler API.

要直接生成字节码,可以使用 ASM 之类的工具。

To generate byte code directly, you can use tools like ASM.

要生成可执行的JAR,请创建 JarOutputStream 声明了主类的清单

To generate an executable JAR, create a JarOutputStream with a manifest that declares the main class.

这篇关于动态创建Java字节码和可运行的jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆