code_junkie

Java Reflection: How to know if a Method is static?

Nov 12th, 2011
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. /**
  2. * Returns the public static methods of a class or interface,
  3. * including those declared in super classes and interfaces.
  4. */
  5. public static List<Method> getStaticMethods(Class<?> clazz) {
  6. List<Method> methods = new ArrayList<Method>();
  7. for (Method method : clazz.getMethods()) {
  8. if (Modifier.isStatic(method.getModifiers())) {
  9. methods.add(method);
  10. }
  11. }
  12. return Collections.unmodifiableList(methods);
  13. }
  14.  
  15. for (Method m : MyClass.class.getMethods()) {
  16. if (Modifier.isStatic(m.getModifiers()))
  17. System.out.println("Static Method: " + m.getName());
  18. }
  19.  
  20. public Method[] getStatics(Class<?> c) {
  21. Method[] all = c.getDeclaredMethods()
  22. List<Method> back = new ArrayList<Method>();
  23.  
  24. for (Method m : all) {
  25. if (Modifier.isStatic(m.getModifiers())) {
  26. back.add(m);
  27. }
  28. }
  29.  
  30. return back.toArray(new Method[back.size()]);
  31. }
Add Comment
Please, Sign In to add comment