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

后端 未结 2 780
渐次进展
渐次进展 2021-01-15 17:30

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

2条回答
  •  渐次进展
    2021-01-15 17:53

    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

提交回复
热议问题