java动态编译以及利用反射进行运行程序

例子;

public static void main(String[] args) throws Exception {
        //动态编译
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //第一个参数:输入流,null表示默认使用system.in键盘输入
        //第二个参数:输出流,null表示默认使用system.out输出到控制台
        //第三个参数:异常打印流,null表示默认使用system.err
        //第四个参数:指定要动态编译的文件集合
        int result = compiler.run(null, null, null, "E:\\test\\myJava\\hello.java");//动态编译指定文件
        System.out.println(result==0?"操作成功":"操作失败");
        
        //通过反射运行编译好的类
        //创建一个url执行将要执行的类存放的文件夹
        URL[] URLS=new URL[]{new URL("file:/E:/test/myJava/")};
        //获取一个类加载器
        URLClassLoader loader = new URLClassLoader(URLS);
        //通过类加载器获取这个类
        Class<?> clazz = loader.loadClass("hello");
        //调用main方法
        Method m = clazz.getDeclaredMethod("main", String[].class);
        //执行main方法
        m.invoke(null,(Object) new String[]{"hzy","I LOVE YOU"});

    }

容易出现的问题:

1)URL[] URLS=new URL[]{new URL("file:/E:/test/myJava/")};创建url的时候最后也要加上一个/,否则会报以下错误:找不到这个类

Exception in thread "main" java.lang.ClassNotFoundException: hello

    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)

2)m.invoke(null,(Object) new String[]{"hzy","I LOVE YOU"});要将其强制转换成object,否则会报以下错误

如果不加编译器会将字符串数组中的值取出来,转换成多个参数的传递

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

猜你喜欢

转载自blog.csdn.net/hzy52013/article/details/80373484