集册 Java实例教程 查找构造函数

查找构造函数

欢马劈雪     最近更新时间:2020-01-02 10:19:05

534
查找构造函数
// from 时 代 J a v a 公 众 号 - nowjava.com



//package com.nowjava;

import java.lang.reflect.Constructor;

import java.util.Arrays;


public class Main {


  public static <T> Constructor<T> findConstructor(Class<T> beanClass, boolean allowNonPublic,

      Class<?>... argumentTypes) {

    Constructor<T>[] candidates = (Constructor<T>[]) (allowNonPublic ? beanClass.getDeclaredConstructors()

        : beanClass.getConstructors());

    sortConstructors(candidates);

    for (Constructor<T> candidate : candidates) {

      if (matchParameterTypes(candidate.getParameterTypes(), argumentTypes)) {

        return candidate;/*时 代 J a v a 公 众 号 提供*/

      }

    }

    return null;

  }


  private static <T> void sortConstructors(Constructor<T>[] constructors) {

    Arrays.sort(constructors, (constructor1, constructor2) -> compareParameterTypes(constructor1.getParameterTypes(),

        constructor2.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];
展开阅读全文