我使用类javax.tools.JavaCompiler(jdk6)来编译源文件,但源文件依赖于某些jar文件.如何设置类路径javax.tools.JavaCompiler?
所以我最近了解到JDK 1.6中提供的新JavaCompiler API.这使得直接从运行代码编译String到.class文件变得非常简单:
String className = "Foo";
String sourceCode = "...";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List<JavaSourceFromString> unitsToCompile = new ArrayList<JavaSourceFromString>()
{{
add(new JavaSourceFromString(className, sourceCode));
}};
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, unitsToCompile).call();
fileManager.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(className + ".class");
IOUtils.copyStream(fis, bos);
return bos.toByteArray();
Run Code Online (Sandbox Code Playgroud)
您可以JavaSourceFromString从Javadoc获取源代码.
这将非常方便地编译sourceCode到Foo.class当前工作目录中.
我的问题是:是否可以直接编译到byte[]数组,并避免File完全处理I/O 的混乱?
我想用来JavaCompiler动态创建一些类.
我找到了javax.tools包的源代码,但是没有实现; 互联网上的一些帖子说它依赖于tools.jar,我不确定是否tools.jar与JRE有关.
那么,我可以在没有安装JDK的JRE环境中运行程序吗?
另一个问题,即实现细节JavaCompiler是什么,是创建一个新的进程来调用javac命令?
谢谢
有没有办法运行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", " "));
}
Run Code Online (Sandbox Code Playgroud)
现在我想用寿命1秒运行该程序并获得输出到字符串变量.有什么办法可以吗?