如何运行JavaCompiler编译的代码?
有没有办法运行JavaCompiler编译的程序? [javax.tools.JavaCompiler]
我的代码:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
task.call();
List<String> returnErrors = new ArrayList<String>();
String tmp = new String();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
tmp = String.valueOf(diagnostic.getLineNumber());
tmp += " msg: "+ diagnostic.getMessage(null);
returnErrors.add(tmp.replaceAll("\n", " "));
}
现在我想以 1 秒的生命周期运行该程序并将输出输出到字符串变量。我有什么办法可以做到这一点吗?
Is there any way to run program compiled by JavaCompiler? [javax.tools.JavaCompiler]
My code:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
task.call();
List<String> returnErrors = new ArrayList<String>();
String tmp = new String();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
tmp = String.valueOf(diagnostic.getLineNumber());
tmp += " msg: "+ diagnostic.getMessage(null);
returnErrors.add(tmp.replaceAll("\n", " "));
}
Now i want to run that program with lifetime 1 sec and get output to string variable. Is there any way i could do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用反射,类似这样的东西:
当然要适应您的需求
You need to use reflection, something like that:
Adapt it of course to suit your needs
您必须将编译后的类添加到当前类路径中。
有多种方法可以做到这一点,具体取决于您的项目的设置方式。下面是一个使用 java.net.URLClassLoader 的实例:
其中“urls”是指向文件系统的 url 列表。
You have to add the compiled class to the current classpath.
There's a number of ways to do that, depending on how your project is set up. Here's one instance using java.net.URLClassLoader:
where "urls" is a list of urls pointing to the filesystem.