I'm trying to make my Main class print out in its console (eclipse) the output from Example1 class (in resources/ as .java file) that depends on Example2 class. I had this idea for grading purposes - to implement it in javafx application that runs a testing class (Example1) on a compiled class file found using FileChooser. I found out about using JavaCompiler, but I could not figure out how to use it to compile a .java file with a dependency on a .class file and execute it...
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class Main {
private static final String EXAMPLE1 = "resources/Example1.java";
private static final String EXAMPLE2 = "resources/Example2.class";
public static void main(String[] args) {
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> d = new DiagnosticCollector<>();
StandardJavaFileManager fm = jc.getStandardFileManager(d, null, null);
List<String> tag = new ArrayList<>();
tag.add("-classpath");
tag.add(System.getProperty("java.class.path") + File.pathSeparator + EXAMPLE2);
File file = new File(EXAMPLE1);
Iterable<? extends JavaFileObject> cu = fm.getJavaFileObjectsFromFiles(Arrays.asList(file));
JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, tag, null, cu);
/*
* ?
*/
}
}
Example1 as .java file in resources/Example1.java
.
public class Example1 {
public static void main(String[] args) {
Example2 ex2 = new Example2(1, 2);
System.out.println("x : " + ex2.x + ", y : " + ex2.y);
System.out.println("sum : " + ex2.sum());
System.out.println("mult : " + ex2.mult());
}
}
Example2 as .class file in resources/Example2.class
public class Example2 {
int x;
int y;
Example2(int x, int y) {
this.x = x;
this.y = y;
}
public int sum() {
return x + y;
}
public int mult() {
return x * y;
}
}