0

I am learing Java Compiler API recently and I write some code that can compile one simple java source code file into a class file, but it can't compile a source code file which refer another class in other source code file. Below is my code:

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

demo/Test.java:

public class Test1 {}

demo/Test2.java:

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

The output:

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)

My question is how to make the compiler know class Test1 is in file Test1.java and this file is in the same source code folder as Test2.java so that it can compile recursively?

kk17
  • 601
  • 6
  • 14
  • I don't think it's a duplicated question. The classpath is use for loading classes not source files. I add classpath option to the getTask method but still have the same ploblem. – kk17 Mar 11 '17 at 11:26
  • So this question won't reopen again? The answers of question [How to set classpath when I use javax.tools.JavaCompiler compile the source ](http://stackoverflow.com/questions/1563909/how-to-set-classpath-when-i-use-javax-tools-javacompiler-compile-the-source) can't solve this problem. @BlackSlash – kk17 Mar 13 '17 at 15:25

0 Answers0