我正在尝试使用javaCompiler动态编译java代码。代码工作gr8但是我需要获取CompilationTask创建的类文件列表。这是源代码:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler ();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager (diagnostics,null,null);
//compile unit
Iterable<? extends JavaFileObject> compilationUnits =fileManager.getJavaFileObjectsFromFiles (sourceFileList);
CompilationTask task = compiler.getTask (null,fileManager, diagnostics, null, null, compilationUnits);
task.call ();
如何获取上述代码生成的类列表,包括内部类。任何帮助将不胜感激。
答案 0 :(得分:2)
The file manager, you provide to the task, is responsible for mapping the abstract JavaFileObject
s to physical files, so it does not only know which resources are accessed or created, it even controls which physical resource will be used. Of course, just locating the created resources after the processing, is possible as well. Here is a simple self-contained example:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null,null);
Path tmp=Files.createTempDirectory("compile-test-");
fileManager.setLocation(StandardLocation.CLASS_OUTPUT,Collections.singleton(tmp.toFile()));
Path src=tmp.resolve("A.java");
Files.write(src, Arrays.asList(
"package test;",
"class A {",
" class B {",
" }",
"}"
));
CompilationTask task = compiler.getTask(null, fileManager,
null, null, null, fileManager.getJavaFileObjects(src.toFile()));
if(task.call()) {
for(JavaFileObject jfo: fileManager.list(StandardLocation.CLASS_OUTPUT,
"", Collections.singleton(JavaFileObject.Kind.CLASS), true)) {
System.out.println(jfo.getName());
}
}
It will list the locations of the generated A.class
and A$B.class
…
答案 1 :(得分:0)
javax.tools.JavaCompiler#getTask()方法采用一个允许设置编译器选项的options参数。使用-d
选项
List<String> options = new ArrayList<String>();
// Sets the destination directory for class files
options.addAll(Arrays.asList("-d","/home/myclasses"));
CompilationTask task = compiler.getTask (null,fileManager, diagnostics, options, null, compilationUnits);
现在获取.class
扩展名