如何使用Java Compile API递归编译?

时间:2017-03-10 11:53:02

标签: java compilation java-compiler-api

我最近学习Java Compiler API,我编写了一些可以将一个简单的java源代码文件编译成类文件的代码,但它无法编译引用其他源代码文件中另一个类的源代码文件。以下是我的代码:

public static void main(String[] args) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        Path path = Paths.get("demo/Test2.java");
        File sourceFile = path.toFile();
        // set compiler's classpath to be same as the runtime's
        String classpath = System.getProperty("java.class.path");
        optionList.addAll(Arrays.asList("-classpath", classpath));
        optionList = Arrays.asList("-d", "demo_class");
        try (StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null)) {
            Iterable<? extends JavaFileObject> fileObjects =
                    fileManager.getJavaFileObjects(sourceFile);
            JavaCompiler.CompilationTask task =
                    compiler.getTask(null, null, null, options, null, fileObjects);
            Boolean result = task.call();
            if (result == null || !result.booleanValue()) {
                throw new RuntimeException(
                        "Compilation failed. class file path:" + sourceFile.getPath());
            }
        }
    }

演示/ Test.java:

public class Test1 {}

演示/ Test2.java:

public class Test2 extends Test1{
    public static void main(String[] args) {
        System.out.println("Test2 compiled.");
    }
}

输出:

demo/Test2.java:2: error: cannot find symbol
public class Test2 extends Test1{
                           ^
  symbol: class Test1
1 error
Exception in thread "main" java.lang.RuntimeException: Compilation failed. class file path:demo/Test2.java
    at test.DynamicCompile.main(DynamicCompile.java:28)

我的问题是如何使编译器知道类Test1在文件Test1.java中,并且此文件与Test2.java在同一源代码文件夹中,以便它可以递归编译?< / p>

0 个答案:

没有答案