如何获取JavaCompiler CompilationTask生成的类文件的列表? [英] How to get list of class files generated by JavaCompiler compilationTask?

查看:88
本文介绍了如何获取JavaCompiler CompilationTask生成的类文件的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javaCompiler动态地编译Java代码。代码适用于gr8,但是我需要获取CompilationTask创建的类文件的列表。这是源代码:

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.

推荐答案

您为任务提供的文件管理器负责映射抽象 JavaFileObject 到物理文件,因此它不仅知道访问或创建了哪些资源,甚至控制了哪些物理资源将会被使用。当然,也可以仅在处理后定位所创建的资源。这是一个简单的独立示例:

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

它将列出生成的<$ c的位置$ c> A.class 和 A $ B.class

这篇关于如何获取JavaCompiler CompilationTask生成的类文件的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆