开发者

Java Reflection - Methods Introspection

Method[] the开发者_如何学JAVAMethods = 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?


The Javadoc makes this pretty clear:

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.

To get at non-public methods, use 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.


From the API doc:

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.

So it gets you only public methods. To get all methods, you have to use getDeclaredMethods() on the class and all its superclasses (via getSuperclass()).

In order to call non-public methods, you can use setAccessible(true) on the Method object (if the security manager allows it).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜