Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only public methods of a class using Java reflection

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!

like image 308
Matter Cat Avatar asked Dec 04 '13 03:12

Matter Cat


People also ask

Which method is used to get methods using reflection?

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.

Can we access private methods using reflection?

You can access the private methods of a class using java reflection package.

Can you name public methods that each Java class has?

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.

Can you access public methods in a private class?

Yes. Well, obviously you can access those methods from within the same class.


1 Answers

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     } } 
like image 75
Sotirios Delimanolis Avatar answered Oct 16 '22 22:10

Sotirios Delimanolis