Java 反射 - 方法自省
Method[] theMethods = myClass.getMethods();
for( Method m : theMethods ){
...
}
该数组是否包含该类的所有方法?公共的、私有的、受保护的以及所有继承的? 我是否可以访问所有这些内容(主要是私有和受保护的内容)?
如果没有,我怎样才能获取一个类的所有方法并访问所有方法?
Method[] theMethods = myClass.getMethods();
for( Method m : theMethods ){
...
}
Will the array include all the methods of the class? public, private, protected and all inherited?
Will I have access to all of them mainly the private and protected ones?
If not, how can I get all the methods of a class and also have access to all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Javadoc 使得这很清楚:
要获取非公共方法,请使用
getDeclaredMethods
。The Javadoc makes this pretty clear:
To get at non-public methods, use
getDeclaredMethods
.要获取类的所有方法,您需要在该类及其所有超类上递归调用 getDeclaredMethods() 。根据您想要实现的目标,您可能需要删除由于方法重载而可能发生的重复项。
To get all methods of a class you need to recursively call getDeclaredMethods() on the class and all it's superclasses. Depending on what you want to achive with it you might need to remove duplicates which can occur due to method overloading.
来自 API 文档:
所以它只能为你提供公共方法。要获取所有方法,您必须在类及其所有超类上使用
getDeclaredMethods()
(通过getSuperclass()
)。为了调用非公共方法,您可以在
Method
对象上使用setAccessible(true)
(如果安全管理器允许)。From the API doc:
So it gets you only public methods. To get all methods, you have to use
getDeclaredMethods()
on the class and all its superclasses (viagetSuperclass()
).In order to call non-public methods, you can use
setAccessible(true)
on theMethod
object (if the security manager allows it).