So I've got this code that compiles a class from a string and then runs it. It works fine from the command line but not in eclipse...
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
public class Another2 {
public static void main(String args[]) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
String temp = "public class ByeWorld {\n" + " public static void main(String args[]) {"
+ " System.out.println(\"First of our Compiled Class\");}}";
JavaFileObject file = new JavaSourceFromString("ByeWorld", temp);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
task.call();
ClassLoader classLoader = Another2.class.getClassLoader();
Class<?> myclass = classLoader.loadClass("ByeWorld");
Method mymethod = myclass.getDeclaredMethod("main", new Class[] { String[].class });
mymethod.invoke(null, new Object[] { null });
}
}
In the command line I get:
$ javac Another2.java
$ java Another2
First of our Compiled Class
But in eclipse I get:
Exception in thread "main" java.lang.ClassNotFoundException: ByeWorld
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at Another2.main(Another2.java:21)
Is something permission-ally going on? is it permanent? And what's my approach for fixing it?
I would bet the directory the file goes in and the directory it's looking to load classes from are different. So essentially it's a working-directory/classpath issue. Remember that Eclipse is trying to make things easier, and it wouldn't expect to look in the current working directory for a .class file.
Try hard-coding where the files should go and be loaded from and see if that changes things. I suspect it will, but can't be sure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With