我正在制作需要动态创建 java 字节码的软件,甚至可能使其成为可运行的 jar。
我当前的想法是创建一个新的 .java 文件并在运行时编译它。我可以创建该文件,但我不确定如何在运行时编译它,并使其成为可运行的 jar。任何帮助将不胜感激。
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 Compiler API .
要直接生成字节码,可以使用 ASM 等工具.
要生成可执行 JAR,请创建 JarOutputStream与 manifest that declares the main class .
关于java - 动态创建java字节码和可运行的jar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11792507/