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).
精彩评论