美文网首页
java 反射学习笔记(二)方法的反射

java 反射学习笔记(二)方法的反射

作者: 夕决_ | 来源:发表于2019-11-17 20:17 被阅读0次

方法的反射

  1. 如何获取某个方法
    方法的名称和方法的参数列表才能唯一决定某个方法
  2. 方法反射操作
    method.invoke(对象,参数列表)

创建一个Class Test
包含两个构造方法,public的无参构造方法 和privte的有参构造方法。
包含两个同名的方法print,参数不同。

class Test {
    public Test(){
        print(1,2);
    }

    private Test(String str){
        print(str,"  "+str);
    }

    public void print(int a, int b){
        System.out.println(a+b);
    }

    private void print(String a, String b){
        System.out.println(a.toUpperCase()+"  ,  "+ b.toLowerCase());
    }
}
}

要获取并调用Test中的两个方法。
通过class.getMethod 获取public的方法
通过getDeclaredMethod获取全部声明的方法
需要设置method.setAccessible(true);来进行权限声明,否则将抛出异常。

public class MethodDemo {

    public static void main(String[] args) {
        // 要获取 print(int a, int b) 方法
        Test test = new Test();
        Class c = test.getClass();

        /**
         * 获取方法名称和参数列表
         * getMethod 获取public的方法
         * getDelcardMethod 自己声明的方法
         */

        try {
            Method m = c.getMethod("print",int.class,int.class);
            Method ms = c.getDeclaredMethod("print",String.class,String.class);
            // 方法的反射操作
            m.invoke(test,2,3);
            ms.setAccessible(true);
            ms.invoke(test,"abc","Def");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

打印结果

3
5
ABC  ,  def

这里使用了Method类,将已知的Test类中的方法转化为对象,并通过method.invoke()方法,进行调用。

然后来通过反射调用构造方法来创建该类的实例:
在不需调用该类的有参的构造方法,只调用无参的构造方法,直接使用class.newInstance()即可。

try {
            Test t = (Test) testClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

打印结果:

3

当需要调用私有的有参方法时,首先需要获取到有参的构造方法,这里使用Constructor将该类的构造方法转化为对象进行操作。
同时必须使用constructor.setAccessible(true); 进行权限声明,否则将抛出无权限访问的异常。

try {
            Constructor constructor = testClass.getDeclaredConstructor(String.class);
            constructor.setAccessible(true);
            Test t = (Test) constructor.newInstance("Test");
        } catch (Exception e) {
            e.printStackTrace();
        }

打印结果:

TEST  ,    test

文章链接:
Java 反射学习笔记(一)认识Class
java 反射学习笔记(二)方法的反射
java 反射学习笔记(三)通过反射机制,绕过编译时泛型检测
java 反射学习笔记(四)反射的基本操作和用法

相关文章

网友评论

      本文标题:java 反射学习笔记(二)方法的反射

      本文链接:https://www.haomeiwen.com/subject/nghmictx.html