反射获取成员方法 并运行ReflectRun

2019-10-08  本文已影响0人  勇者与王者
package Day32_Reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author quzheng
 * @Date 2019/10/7 23:20
 * @Version 1.0
 *
 * 反射 获取空参数成员方法 并运行
 *
 * 反射 获取有参数的成员方法 并运行
 */
public class ReflectRun {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class c = Class.forName("Day32_Reflection.Person");

        // Method[] getMethods() 获取的是class 文件中的所有公共成员方法,包括继承的
        Method[] ms = c.getMethods();
        for (Method m : ms){
//            System.out.println(m);
        }

        // 获取指定的方法 getMethod(String methodName,Class...c)
        Method m1 = c.getMethod("eat");
        System.out.println(m1);

        // 使用Method 类的方法  invoke(Object obj,Object...o)  运行获取到的方法
        // invoke(Object obj,Object...o) 第一个参数为对象,第二个参数为 方法的参数列表
        Object obj = c.newInstance();
        m1.invoke(obj);

        // 调用 Class 类的方法 getMethod() 获取指定的方法
        Method m2 = c.getMethod("sleep",String.class,int.class,double.class);
        m2.invoke(obj,"休眠",100,888.99);

    }
}

上一篇 下一篇

猜你喜欢

热点阅读