集册 Java实例教程 使用反射的参数调用方法

使用反射的参数调用方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

430
使用反射的参数调用方法

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;
/* 
*来 自
 时 代 J a v a - nowjava.com
*/

import java.util.Arrays;


public class InvokeMain {

    public static void main(String... args) {

        try {

            Class<?> c = Class.forName(args[0]);

            Class[] argTypes = new Class[] { String[].class };

            Method main = c.getDeclaredMethod("main", argTypes);

            String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);

            System.out.format("invoking %s.main()%n", c.getName());

            main.invoke(null, (Object) mainArgs);


            // production code should handle these exceptions more gracefully

        } catch (ClassNotFoundException x) {
        /**
        来 自 时 代 J a v a - N o w J a v a . c o m
        **/

            x.printStackTrace();

        } catch (NoSuchMethodException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        } catch (InvocationTargetException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文