package com.liming.dynamiccompile;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class DynamicCompile {
public static void main(String[] args){
System.out.println("Hello DynamicCompile");
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
if(0 == javaCompiler.run(null,null,null,"res/HelloWorld.java")){
try {
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file://"+System.getProperty("user.dir")+"/res/HelloWorld")});
Class<?> xlass = urlClassLoader.loadClass("HelloWorld");
Constructor<?> c = xlass.getConstructor();
Object o = c.newInstance();
Method m = xlass.getMethod("main", String[].class);
Object[] argx = {new String[]{"人在江湖飘飘","飞出恩怨两刀","江湖飘"}};
m.invoke(o,argx);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
网友评论