反射获取成员方法并使用

Method[] getMethods()  返回包含一个数组 方法对象反射由此表示的类或接口的所有公共方法类对象包括那些由类或接口和那些从超类和超接口继承的声明

public class ReflectDemo03 {
    public static void main(String[] args) throws ClassNotFoundException {
        //获取Class对象
        Class<?> c = Class.forName("com.reflect_02.Student");

        //Method[] getMethods()
        //返回包含一个数组 方法对象反射由此表示的类或接口的所有公共方法 类对象,包括那些由类或接口和那些从超类和超接口继承的声明。
        Method[] methods = c.getMethods();
        for (Method method : methods){
            System.out.println(method);
        }
    }
}

该方法的运行结果:(包括继承的方法)

Method[] getDeclaredMethods()  返回包含一个数组 方法对象反射的类或接口的所有声明的方法,通过此表示 类对象,包括公共,保护,默认(包)访问和私有方法但不包括继承的方法
public class ReflectDemo03 {
    public static void main(String[] args) throws ClassNotFoundException {
        //获取Class对象
        Class<?> c = Class.forName("com.reflect_02.Student");

        //Method[] getDeclaredMethods()
        //返回包含一个数组 方法对象反射的类或接口的所有声明的方法,通过此表示 类对象,包括公共,保护,默认(包)访问和私有方法,但不包括继承的方法。
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods){
            System.out.println(method);
        }
    }
}

该方法的运行结果:

Method getMethod(String name, 类<?>... parameterTypes)  返回一个 方法对象,它反映此表示的类或接口的指定公共成员方法 类对象

Object invoke(Object obj, Object... args)  在具有指定参数的 方法对象上调用此 方法对象表示的底层方法。

参数解释:

Object 返回值类型

obj 调用方法的对象

args 方法需要的参数

public class ReflectDemo03 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //获取Class对象
        Class<?> c = Class.forName("com.reflect_02.Student");

        //获取构造方法对象
        Constructor<?> con = c.getConstructor();
        //创建对象
        Object obj = con.newInstance();

        //Method getMethod(String name, 类<?>... parameterTypes)
        //返回一个 方法对象,它反映此表示的类或接口的指定公共成员方法 类对象。
        Method m1 = c.getMethod("method1");

        //Object invoke(Object obj, Object... args)
        //在具有指定参数的 方法对象上调用此 方法对象表示的底层方法。
        m1.invoke(obj);
    }
}

Student类中的method1方法:

运行结果:

public class ReflectDemo03 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //获取Class对象
        Class<?> c = Class.forName("com.reflect_02.Student");

        //获取构造方法对象
        Constructor<?> con = c.getConstructor();
        //创建对象
        Object obj = con.newInstance();

        //Method getDeclaredMethod(String name, 类<?>... parameterTypes)
        //返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 类对象。
        Method f1 = c.getDeclaredMethod("function");
        f1.setAccessible(true);

        //Object invoke(Object obj, Object... args)
        //在具有指定参数的 方法对象上调用此 方法对象表示的底层方法。
        f1.invoke(obj);
    }
}

猜你喜欢

转载自www.cnblogs.com/pxy-1999/p/13173124.html
今日推荐