find Method - Java Reflection

Java examples for Reflection:Method

Description

find Method

Demo Code



//package com.java2s;

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

public class Main {
  public static Method findMethod(Class<?> beanClass, boolean allowNonPublic, String name, Class<?>[] argumentTypes) {
    Method[] candidates = allowNonPublic ? beanClass.getDeclaredMethods() : beanClass.getMethods();
    sortMethods(candidates);/*from  w w  w  .j  a v a 2s .  co  m*/
    for (Method candidate : candidates) {
      if (candidate.getName().equals(name) && matchParameterTypes(candidate.getParameterTypes(), argumentTypes)) {
        return candidate;
      }
    }
    return null;
  }

  private static <T> void sortMethods(Method[] methods) {
    Arrays.sort(methods,
        (method1, method2) -> compareParameterTypes(method1.getParameterTypes(), method2.getParameterTypes()));
  }

  private static boolean matchParameterTypes(Class<?>[] parameterTypes, Class<?>[] argumentTypes) {
    if (parameterTypes.length == argumentTypes.length) {
      boolean match = true;
      for (int i = 0; i < parameterTypes.length; i++) {
        if (!parameterTypes[i].isAssignableFrom(argumentTypes[i])) {
          match = false;
          break;
        }
      }
      return match;
    } else {
      return false;
    }
  }

  private static int compareParameterTypes(Class<?>[] parameterTypes1, Class<?>[] parameterTypes2) {
    if (parameterTypes1.length != parameterTypes2.length) {
      return 0;
    } else {
      int result = 0;
      for (int i = 0; result == 0 && i < parameterTypes1.length; i++) {
        Class<?> parameterType1 = parameterTypes1[i];
        Class<?> parameterType2 = parameterTypes2[i];
        if (!parameterType1.equals(parameterType2)) {
          if (parameterType1.isAssignableFrom(parameterType2)) {
            result = 1;
          } else if (parameterType2.isAssignableFrom(parameterType1)) {
            result = -1;
          }
        }
      }
      return result;
    }
  }
}

Related Tutorials