java反射中getMethod getDeclaredMethod .

来源:互联网 发布:免费下载安装淘宝网 编辑:程序博客网 时间:2024/06/05 06:19

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

 

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

1、getDeclaredMethods和getMethods的区别

 MethodgetDeclaredMethod(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.


 MethodgetMethod(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方法。

 

注:

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

 

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

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

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

 


原创粉丝点击