I writed a code that generates two class which I write them to buffer and compile them with JavaCompiler. My classes are like this in .java files;
public class A{
public A() { }
public String toString(){ return "A";}
}
and
public class B extends ArrayList<A> {
public B() {
super();
}
public void addItem(A a)
{
this.add(a);
}
public void print() {
this.print();
}
}
something like this.
However, the name of the classes are randomly generated and when I create the file it gives an error like this;
symbol: class A
location: class B
./src/A.java:4: error: cannot find symbol
(4th line is the "...extends ArrayList..." and there is a ^ symbol under A)
My code generator compiles like this;
First I fill the buffer with my template for A type classes then compile like this:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, f.getPath());
after that I create another buffer and fill it with my template for B type classes then compile like this;
System.out.println(f.getParentFile().getPath());
compiler.run(null, null, null, f.getPath());
f is;
f = new File(("./src/" + name + ".java"));
How can I solve this problem?
As mentioned in the comment the compiler need to know about class
A
when classB
is compiled. In the example below we add the output directory for the compiled classes/tmp/bin/
to the classpath for the compiler inoptionList
.You could either prevent to create the source files on the filesystem, if you don't need them as such
or you create the Java source files on the file system. Similar code as above with a small change for the
compilationUnits
. It's assumed the files have been already stored on the given location.