您的位置:首页 > 编程语言 > Java开发

Java中的反射reflect之getDeclaredMethods和getMethods

2014-07-15 14:12 417 查看

试用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 the
public member methods of the class or interface represented by this
Class
object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
由此可见,getDeclaredMethod*()获取的是类自身声明的所有方法,包含public、protected和private方法。getMethod*()获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。

实例一:getDeclaredMethod和getMethod的区别

Say.java:

?
SayTest.java

?
当使用say方法里的//1语句时,main函数抛出异常,可见使用getMethod时,因为sayHi是保护方法,获取方法sayHi失败

?
当使用say方法里的//2语句时,可以正常调用

?
可见,不能用java.lang.Class.getMethod方法获取自身的非public方法,用java.lang.Class.getDeclaredMethod方法可以。

实例二:getDeclaredMethods和getMethods的区别

ReflectionUtils.java

?
测试类 SayTest.java

?
输出:

?
可见,调用getMethods方法输出的是自身的public方法和父类Object的public方法。调用getDeclaredMethods方法输出的是自身的public、protected、private方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: