I'm trying to use reflection to grab all public methods that are declared explicitly in the class (so c.getMethods()
won't work since it grabs superclass methods too). I can use
Method[] allMethods = c.getDeclaredMethods();
to grab methods from just that class, but I only want to use public ones.
At this point, I'm trying to grab modifiers and do certain actions based on this, but for some reason the modifier value shown in the debugger and the modifier value output isn't the same. For example, I have a private getNode
method that, while the "modifiers" value appears as 2
in the debugger, it outputs as "1"
when I do System.out.println(c.getModifiers())
. Weird. Is there another way to get just public methods, or am I missing something obvious? Thanks for any help!
The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.
You can access the private methods of a class using java reflection package.
The public methods include that are declared by the class or interface and also those that are inherited by the class or interface. Also, the getMethods() method returns a zero length array if the class or interface has no public methods or if a primitive type, array class or void is represented in the Class object.
Yes. Well, obviously you can access those methods from within the same class.
I don't know how you are using Modifier
, but here's how it's meant to be used
Method[] allMethods = Test.class.getDeclaredMethods(); for (Method method : allMethods) { if (Modifier.isPublic(method.getModifiers())) { System.out.println(method); // use the method } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With