【发布时间】:2011-01-08 23:00:07
【问题描述】:
所以我最近了解到 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();
您可以从Javadoc 获取到JavaSourceFromString 的源代码。
这将非常方便地将当前工作目录中的sourceCode 编译为Foo.class。
我的问题是:是否可以直接编译为byte[] 数组,并避免完全处理File I/O 的麻烦?
【问题讨论】:
标签: java compilation in-memory jsr199