Unable to compile default package class referred in other classes using JavaCompiler

376 Views Asked by At

I have a situation where I need to compile classes dynamically.

Following is the structure in which my java classes have been organized.

// no package 
public class A{
}

package test ;

public class B{
      A obj;
     //other java code
}

where A is a class with default package, and B is a class with package name test. B has A as a attribute.

Files are saved in their respective folders( as per package )

I fail to compile this with JAVA Compiler API.

3

There are 3 best solutions below

0
On

You cannot refer to classes in the default package from classes in other packages. This has been the case since 2001. See the Release Notes for Java 1.4.

1
On

You should be able to set the classpath variable as an option.

List<String> optionList = new ArrayList<String>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
String path =....
optionList.addAll(Arrays.asList("-classpath",path ));
JavaCompiler.CompilationTask task = compiler.getTask(null, null, null,optionList,null,fileObjects);
1
On