Reputation: 20470
clazz.getDeclaredMethods()
will returns all methods, but I only want those public static
methods, how do I make it ?
Upvotes: 1
Views: 227
Reputation: 55
Try using:
Modifier.isStatic(method.getModifiers()).
Example:
public static List<Method> getStaticMethods(Class<?> clazz)
{
List<Method> methods = new ArrayList<Method>();
for (Method method : clazz.getMethods())
{
if (Modifier.isStatic(method.getModifiers()))
{
methods.add(method);
}
}
return Collections.unmodifiableList(methods);
}
Upvotes: 1
Reputation: 280168
You need to check with the Modifier
class after calling getModifiers
on the Method
objects
public static void main(String[] args) throws Exception { //Read user input into the array
Method method = Main.class.getDeclaredMethod("main", String[].class);
int modifiers = method.getModifiers();
System.out.println(modifiers);
System.out.println(Modifier.isStatic(modifiers));
System.out.println(Modifier.isPublic(modifiers));
System.out.println(Modifier.isAbstract(modifiers));
}
prints
9
true
true
false
The int
value holds information in specific bit positions for static
, public
, etc. modifiers.
Upvotes: 5
Reputation: 9162
you should iterate over the methods returned and check getModifiers() method. If it returns STATIC or not.
More info in the javadoc
Upvotes: 1