从String编译java源代码而不写入文件[重复]

问题描述 投票:12回答:2

这个问题在这里已有答案:

Here我找到了一些很好的例子:

// Prepare source somehow.
String source = "package test; public class Test { static { System.out.println(\"hello\"); } public Test() { System.out.println(\"world\"); } }";

// Save source in .java file.
File root = new File("/java"); // On Windows running on C:\, this is C:\java.
File sourceFile = new File(root, "test/Test.java");
sourceFile.getParentFile().mkdirs();
new FileWriter(sourceFile).append(source).close();

// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());

// Load and instantiate compiled class.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
Object instance = cls.newInstance(); // Should print "world".
System.out.println(instance); // Should print "test.Test@hashcode".

问题:如果不写入文件,是否可以实现完全相同的功能?

@Edit:更确切地说:我知道如何从字符串编译(重载JavaFileObject)。但在这之后,我不知道如何加载该类。我可能错过了输出写入部分,但这也是我不想做的事情。

@ Edit2对于任何有兴趣的人,我创建了这个小项目来实现讨论的功能:https://github.com/Krever/JIMCy

java
2个回答
4
投票

好的,所以here是一个使用JavaCompilerString输入编译的例子。 this file是它的核心。

this file中,我加载了编译的类。您会注意到我还使用正则表达式检测包和类名。


至于输出,如果你想在内存中这样做,看来你可以这样做,如果你实现自己的JavaFileManager;但是我从来没有尝试过!

请注意,您可以通过扩展ForwardingJavaFileManager来调试很容易发生的事情


0
投票

不完全是你要求的,但Groovy的Java库使得从String编译和计算表达式变得容易。语法不同但与Java非常相似,因此如果您可以更改要编译的字符串,以便它们使用Groovy而不是Java,则任务将非常简单。有关代码示例,请参阅Embedding Groovy

© www.soinside.com 2019 - 2024. All rights reserved.