美文网首页
Java动态编译的使用

Java动态编译的使用

作者: 手打小黑板 | 来源:发表于2020-02-12 10:15 被阅读0次
    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();
                }
    
            }
    
    
    
    
    
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Java动态编译的使用

          本文链接:https://www.haomeiwen.com/subject/uayqfhtx.html