Java 方法反射的基本操作

方法的反射:
1.获取A类中的print(int,int)方法:
①要获取一个方法就是获取类的信息,获取类的信息首先要获取类的类类型
A a1=new A();  Class c= a1.getClass();
②获取方法 由名称和参数列表来决定,getMethod获取的是public方法,getDelcaredMethod获取自己声明的方法
Method m =c.getMethod(methodName,paramtypes);//paramtypes可以用数组的形式表示new Class[]{int.class,int.class},也可以直接列举类类型
2.方法的反射操作:是用m对象来进行方法调用,和a1.print(10,20)调用的方法相同m.invoke(a1,new Object[]{10,20})
Object o=m.invoke(对象名,参数);//方法如果没有返回值返回null,如果有返回值返回具体值,参数可用数组的方式表示,也可以直接列举,没有参数就不写


方法的反射:
1. 方法名称加参数列表可以唯一确定一个方法
2. 通过方法对象来实现方法的功能,即把实例对象当成参数传给方法对象

Here is an example:
There is a class A:
class A{void printInfo(String s1, String s2){System.out.println(s1 + s2);}}
Implement the class:
A a = new A();
Class c = a.getClass();
Method m = c.getMethod("printInfo", String.class, String.class);
//getMethod方法只能获得public方法
//getDeclaredMethod方法能获得所有自己声明的方法
//you can write the above code like following:
Method m = c.getMethod("printInfo", new Object[]{String.class,String.class});

Object o = m.invoke(a, "Hello ", "World!");//Here, o = null
//You can also write like:
Object o = m.invoke(a, new Object[]{"Hello ","World!"});
//The above code just like:
a.printInfo("Hello ","World!");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值