How to get list of class files generated by JavaCompiler compilationTask?

北城以北 提交于 2019-12-24 10:59:13

问题


I am trying to compile java code dynamically using javaCompiler. Code works gr8 however I need to get the list of class files created by CompilationTask. Here is source code:

    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 ();

How can I get the list of classes generated by above code, including inner classed. any help would be much appreciated.


回答1:


The file manager, you provide to the task, is responsible for mapping the abstract JavaFileObjects 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




回答2:


The javax.tools.JavaCompiler#getTask() method takes an options parameter that allows to set compiler options. Set the destination directory for class files using -d option

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);

Now get all the files with .class extentions



来源:https://stackoverflow.com/questions/39239285/how-to-get-list-of-class-files-generated-by-javacompiler-compilationtask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!