Problem
I'm trying to run a java program which is contained in a string but it gives me a runtime exception i.e. ClassNotFoundException
for Test
class.
Error
Exception in thread "main" java.lang.ClassNotFoundException: Test at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
Code
public class CompileString {
public static void main(String[] args) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
String program = "class Test{" + " public static void main (String [] args){"
+ " System.out.println (\"Hello, World\");"
+ " System.out.println (args.length);" + " }" + "}";
Iterable<? extends JavaFileObject> fileObjects;
fileObjects = getJavaSourceFromString(program);
compiler.getTask(null, null, null, null, null, fileObjects).call();
Class<?> clazz = Class.forName("Test");
Method m = clazz.getMethod("main", new Class[] { String[].class });
Object[] _args = new Object[] { new String[0] };
m.invoke(null, _args);
}
static Iterable<JavaSourceFromString> getJavaSourceFromString(String code) {
final JavaSourceFromString jsfs;
jsfs = new JavaSourceFromString("code", code);
return new Iterable<JavaSourceFromString>() {
public Iterator<JavaSourceFromString> iterator() {
return new Iterator<JavaSourceFromString>() {
boolean isNext = true;
public boolean hasNext() {
return isNext;
}
public JavaSourceFromString next() {
if (!isNext)
throw new NoSuchElementException();
isNext = false;
return jsfs;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
Another class:
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') +
Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
How can solve this problem, please help me?
Here is the error if i try to change any code in the String which gives me compile error as well means everything working right then why it not found the Test
class?
/Code.java:1: error: ';' expected class Test{ public static void main (String [] args){ System.out.println >("Hello, World") System.out.println (args.length); }}
And if i am try to execute from command prompt it will working correctly..then whats the problem with IDE i am using Eclipse?
hear is image of eclipse .class file create at run time but why i can't access that is there any other way please tell me. i am not able to access the Test.class because it created the outside of the project it required to create in same folder that other .class file is created here is working directory image