private static Constructor findCompatibleConstructor()

in spark-load/spark-load-common/src/main/java/org/apache/doris/common/jmockit/ConstructorReflection.java [120:157]


    private static <T> Constructor<T> findCompatibleConstructor(Class<?> theClass, Class<?>[] argTypes) {
        if (theClass == null || argTypes == null) {
            throw new IllegalArgumentException();
        }
        Constructor<T> found = null;
        Class<?>[] foundParameters = null;
        Constructor<?>[] declaredConstructors = theClass.getDeclaredConstructors();
        Constructor[] declaredConstructorsArray = declaredConstructors;

        for (Constructor<?> declaredConstructor : declaredConstructorsArray) {
            Class<?>[] declaredParamTypes = declaredConstructor.getParameterTypes();
            int gap = declaredParamTypes.length - argTypes.length;
            if (gap == 0 && (ParameterReflection.matchesParameterTypes(declaredParamTypes, argTypes)
                    || ParameterReflection.acceptsArgumentTypes(declaredParamTypes, argTypes))
                    &&
                    (found == null || ParameterReflection.hasMoreSpecificTypes(declaredParamTypes, foundParameters))) {
                found = (Constructor<T>) declaredConstructor;
                foundParameters = declaredParamTypes;
            }
        }

        if (found != null) {
            return found;
        } else {
            Class<?> declaringClass = theClass.getDeclaringClass();
            Class<?>[] paramTypes = declaredConstructors[0].getParameterTypes();
            // check if this constructor is belong to a inner class
            // the parameter[0] of inner class's constructor is a instance of outer class
            if (paramTypes[0] == declaringClass && paramTypes.length > argTypes.length) {
                throw new IllegalArgumentException(
                        "Invalid instantiation of inner class; use newInnerInstance instead");
            } else {
                String argTypesDesc = ParameterReflection.getParameterTypesDescription(argTypes);
                throw new IllegalArgumentException(
                        "No compatible constructor found: " + theClass.getSimpleName() + argTypesDesc);
            }
        }
    }