反射获取成员方法并使用【应用】

Class类获取成员方法对象的方法

  • 方法分类

    方法名 说明
    Method[] getMethods() 返回所有公共成员方法对象的数组,包括继承的
    Method[] getDeclaredMethods() 返回所有成员方法对象的数组,不包括继承的
    Method getMethod(String name, Class... parameterTypes) 返回单个公共成员方法对象
    Method getDeclaredMethod(String name, Class... parameterTypes) 返回单个成员方法对象
  • 示例代码

public class ReflectDemo01 {
    public static void main(String[] args) throws Exception {
        //获取Class对象
        Class c = Class.forName("com.leon_02.Student");

        //Method[] getMethods() 返回一个包含 方法对象的数组, 方法对象反映由该 Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象以及从超类和超级接口继承的类
        //Method[] getDeclaredMethods() 返回一个包含 方法对象的数组, 方法对象反映由 Class对象表示的类或接口的所有声明方法,包括public,protected,default(package)访问和私有方法,但不包括继承方法
//        Method[] methods = c.getMethods();
        Method[] methods = c.getDeclaredMethods();
        for(Method method : methods) {
            System.out.println(method);
        }
        System.out.println("--------");

        //Method getMethod(String name, Class... parameterTypes) 返回一个 方法对象,该对象反映由该 Class对象表示的类或接口的指定公共成员方法
        //Method getDeclaredMethod(String name, Class... parameterTypes) 返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 Class对象
        //public void method1()
        Method m = c.getMethod("method1");

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

//        obj.m();

        //在类或接口上提供有关单一方法的信息和访问权限
        //Object invoke(Object obj, Object... args) 在具有指定参数的指定对象上调用此 方法对象表示的基础方法
        //Object:返回值类型
        //obj:调用方法的对象
        //args:方法需要的参数
        m.invoke(obj);

//        Student s = new Student();
//        s.method1();
    }
}

Method类用于执行方法的方法

方法名 说明
Objectinvoke(Object obj,Object... args) 调用obj对象的成员方法,参数是args,返回值是Object类型

反射获取成员方法并使用练习【应用】

  • 案例需求

    • 通过反射获取成员方法并调用

  • 代码实现

    • 学生类:参见上方学生类

    • 测试类

public class ReflectDemo02 {
    public static void main(String[] args) throws Exception {
        //获取Class对象
        Class c = Class.forName("com.leon_02.Student");

        //Student s = new Student();
        Constructor con = c.getConstructor();
        Object obj = con.newInstance();

        //s.method1();
        Method m1 = c.getMethod("method1");
        m1.invoke(obj);

        //s.method2("林青霞");
        Method m2 = c.getMethod("method2", String.class);
        m2.invoke(obj,"林青霞");

//        String ss = s.method3("林青霞",30);
//        System.out.println(ss);
        Method m3 = c.getMethod("method3", String.class, int.class);
        Object o = m3.invoke(obj, "林青霞", 30);
        System.out.println(o);

        //s.function();
//        Method m4 = c.getMethod("function"); //NoSuchMethodException: com.itheima_02.Student.function()
        Method m4 = c.getDeclaredMethod("function");
        m4.setAccessible(true);
        m4.invoke(obj);
    }
}

 

你可能感兴趣的:(反射获取成员方法并使用【应用】)