Reputation: 183
To display all the methods of the class, whose name is entered through user-input at run-time in the form of a String, I do:
// String s is the class name entered
if (Class.forName(s).getDeclaredMethods().length > 0) {
for (int i = 0; i < Class.forName(s).getDeclaredMethods().length; i++) {
System.out.println(Class.forName(s).getDeclaredMethods()[i].toString());
}
}
However, if I need to display just the public methods, what do I add?
Upvotes: 5
Views: 4138
Reputation: 11969
You can get the modifiers using getModifiers()
. Here is an idea (not tested)
for(Method m : Class.forName(s).getDeclaredMethods()) {
if(m.getModifiers() == Modifier.PUBLIC) {
//Do something
}
}
There is also a isPublic
method in the Modifier
class (doc)
Upvotes: 2
Reputation: 172378
You can try like this:
if (Modifier.isPublic(method.getModifiers()))
{
//Yes the method is PUBLIC
}
Refer getModifier:
Returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers.
Upvotes: 17
Reputation: 533442
I might write it like this.
for (Method m : Class.forName(s).getDeclaredMethods()) {
boolean isPublic = (m.getModifiers() & Modifier.PUBLIC) != 0;
System.out.println(m + " isPublic: " + isPublic);
}
Upvotes: 8