Find a Method on the supplied class with the supplied name and no parameters

 
import java.lang.reflect.Method;
import java.util.Arrays;

public class Main {
  public static void main(String[] argv){
    Method m = findMethod(new MyClass().getClass(), "getCount");
    System.out.println(m);
    
    m = findMethod(new MyClass().getClass(), "setCount");
    System.out.println(m);
  }
  
  
  public static Method findMethod(Class clazz, String name) {
    return findMethod(clazz, name, new Class[0]);
  }

  public static Method findMethod(Class clazz, String name, Class[] paramTypes) {
    Class searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
      Method[] methods = (searchType.isInterface() ? searchType.getMethods()
          : searchType.getDeclaredMethods());
      for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (name.equals(method.getName())
            && Arrays.equals(paramTypes, method.getParameterTypes())) {
          return method;
        }
      }
      searchType = searchType.getSuperclass();
    }
    return null;
  }

}

class MyClass extends ParentClass {
  private int count;

  MyClass(int c) {
    count = c;
  }

  MyClass() {
    count = 0;
  }

  void setCount(int c) {
    count = c;
  }

  int getCount() {
    return count;
  }

  void showcount() {
    System.out.println("count is " + count);
  }
}
class ParentClass{
  
  void fromParentClass(){
  
  }

}
  
Home 
  Java Book 
    Runnable examples  

Reflection Method:
  1. Convert method to property name
  2. Find a Method on the supplied class with the supplied name and no parameters
  3. Find a Method on the supplied class with the supplied name and parameter types
  4. Get all methods from a class
  5. Get constructor and its parameters and call constructor with parameter
  6. Get method by parameter type
  7. Get all declared methods from a class, not inherited
  8. Get specific method by its name and parameters
  9. Get Static Method
  10. Get the current running method name
  11. Invoke a method with Reflection
  12. Invoke a method on an object with parameters
  13. Invoke a method with 2 arguments
  14. Invoke private method
  15. Method modifiers: isSynthetic(), isVarArgs(), isBridge()
  16. Method return type, parameter's type
  17. Method signature
  18. Modifier public, private, protected, static, final, abstract
  19. Modifier checker checks all possible modifiers for a method
  20. Sort methods according to their name, number of parameters, and parameter types.