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?