java反射中getMethod getDeclaredMethod

原文地址:http://www.cnblogs.com/jianjianjiao/articles/1853409.html


试用Java中的反射reflect之getDeclaredMethods和getMethods

目的:根据类名、方法名以及方法对应的参数,获取方法,并实现方法的调用

1、getDeclaredMethods和getMethods的区别

 Method getDeclaredMethod(String name, Class... parameterTypes) 
          Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
 Method[] getDeclaredMethods() 
          Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.


 Method getMethod(String name, Class... parameterTypes) 
          Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
 Method[] getMethods() 
          Returns an array containing Method objects reflecting all thepublic member methods of the class or interface represented by this Classobject, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

由此可见,getDeclaredMethod*()获取的是类自身声明的所有方法,包含public、protected和private方法。getMethod*()获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。


楼主注:因此用反射调用私有方法,必须用getDeclaredMethod方法,同时注意调用私有方法和改变私有变量一样,必须在调用前设置 method.setAccessible(true),这就是传说中的暴力反射吧!


另外注意的一点如果是boolean型的参数,得到方法的时候需要用boolean.class或者Boolean.TYPE,不能用Boolean.class。


得到方法的时候可以用Method.toString()方法,打印出函数的完整原型,如:

protected java.lang.String com.unity3d.player.UnityPlayer.getCPUType()


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值