Код: Выделить всё
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 diagnostics = new DiagnosticCollector();
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 myclass = classLoader.loadClass("ByeWorld");
Method mymethod = myclass.getDeclaredMethod("main", new Class[] { String[].class });
mymethod.invoke(null, new Object[] { null });
}
}
Код: Выделить всё
$ javac Another2.java
$ java Another2
First of our Compiled Class
Код: Выделить всё
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)
Подробнее здесь: https://stackoverflow.com/questions/859 ... m-a-string