Selects the best constructor for the given argument types.
@param <T>
@param constructors
@param argTypes
@return constructor, or {@code null}
@throws AmbiguousSignatureMatchException if multiple constructors match equally
174227
public static <T> Constructor<T> bestConstructor(Constructor<T>[] constructors, Class<?>[] argTypes) throws AmbiguousConstructorMatchException {
        try {
            return best(constructors, collectSignatures(constructors), collectVarArgs(constructors), argTypes);
        } catch (AmbiguousSignatureMatchException e) {
            throw new AmbiguousConstructorMatchException(e, constructors);
        }
    }
941710
protected MethodNode checkGroovyStyleConstructor(final ClassNode node, final ClassNode[] arguments, final ASTNode source) {
        if (node.equals(ClassHelper.OBJECT_TYPE) || node.equals(ClassHelper.DYNAMIC_TYPE)) {
            // in that case, we are facing a list constructor assigned to a def or object
            return null;
        }
        List<ConstructorNode> constructors = node.getDeclaredConstructors();
        if (constructors.isEmpty() && arguments.length == 0) {
            return null;
        }
        List<MethodNode> constructorList = findMethod(node, "<init>", arguments);
        if (constructorList.isEmpty()) {
            if (isBeingCompiled(node) && arguments.length == 1 && LINKEDHASHMAP_CLASSNODE.equals(arguments[0])) {
                // there will be a default hash map constructor added later
                ConstructorNode cn = new ConstructorNode(Opcodes.ACC_PUBLIC, new Parameter[]{
                        new Parameter(LINKEDHASHMAP_CLASSNODE, "args")
                }, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE);
                return cn;
            } else {
                addStaticTypeError("No matching constructor found: " + node + toMethodParametersString("<init>", arguments), source);
                return null;
            }
        } else if (constructorList.size() > 1) {
            addStaticTypeError("Ambiguous constructor call " + node + toMethodParametersString("<init>", arguments), source);
            return null;
        }
        return constructorList.get(0);
    }
850471
private static Object callConstructor(final Class<?> cls, final Class<?>[] argTypes,
      final Object[] args) {
    try {
      final Constructor<?> cons = cls.getConstructor(argTypes);
      return cons.newInstance(args);
    } catch (final InvocationTargetException e) {
      throw getCause(e);
    } catch (final IllegalAccessException | NoSuchMethodException | InstantiationException e) {
      throw new IllegalStateException(e);
    }
  }
855710
protected static boolean typeCheckMethodArgumentWithGenerics(ClassNode parameterType, ClassNode argumentType, boolean lastArg) {
        if (UNKNOWN_PARAMETER_TYPE == argumentType) {
            // called with null
            return !isPrimitiveType(parameterType);
        }
        if (!isAssignableTo(argumentType, parameterType) && !lastArg) {
            // incompatible assignment
            return false;
        }
        if (!isAssignableTo(argumentType, parameterType) && lastArg) {
            if (parameterType.isArray()) {
                if (!isAssignableTo(argumentType, parameterType.getComponentType())) {
                    return false;
                }
            } else {
                return false;
            }
        }
        if (parameterType.isUsingGenerics() && argumentType.isUsingGenerics()) {
            GenericsType gt = GenericsUtils.buildWildcardType(parameterType);
            if (!gt.isCompatibleWith(argumentType)) {
                boolean samCoercion = isSAMType(parameterType) && argumentType.equals(CLOSURE_TYPE);
                if (!samCoercion) return false;
            }
        } else if (parameterType.isArray() && argumentType.isArray()) {
            // verify component type
            return typeCheckMethodArgumentWithGenerics(parameterType.getComponentType(), argumentType.getComponentType(), lastArg);
        } else if (lastArg && parameterType.isArray()) {
            // verify component type, but if we reach that point, the only possibility is that the argument is
            // the last one of the call, so we're in the cast of a vargs call
            // (otherwise, we face a type checker bug)
            return typeCheckMethodArgumentWithGenerics(parameterType.getComponentType(), argumentType, lastArg);
        }
        return true;
    }
457237
@SuppressWarnings("unused")
    public Method getOrigin(Object instance, String methodWithTypeAndSignature) throws Throwable {
        if (!isMocked(instance)) {
            return null;
        }

        Matcher methodComponents = methodPattern.matcher(methodWithTypeAndSignature);
        boolean wasFound = methodComponents.find();
        if (!wasFound) {
            throw new IllegalArgumentException();
        }
        String argTypeNames[] = methodComponents.group(3).split(",");

        ArrayList<Class<?>> argTypes = new ArrayList<>(argTypeNames.length);
        for (String argTypeName : argTypeNames) {
            if (!argTypeName.equals("")) {
                switch (argTypeName) {
                    case "byte":
                        argTypes.add(Byte.TYPE);
                        break;
                    case "short":
                        argTypes.add(Short.TYPE);
                        break;
                    case "int":
                        argTypes.add(Integer.TYPE);
                        break;
                    case "long":
                        argTypes.add(Long.TYPE);
                        break;
                    case "char":
                        argTypes.add(Character.TYPE);
                        break;
                    case "float":
                        argTypes.add(Float.TYPE);
                        break;
                    case "double":
                        argTypes.add(Double.TYPE);
                        break;
                    case "boolean":
                        argTypes.add(Boolean.TYPE);
                        break;
                    case "byte[]":
                        argTypes.add(byte[].class);
                        break;
                    case "short[]":
                        argTypes.add(short[].class);
                        break;
                    case "int[]":
                        argTypes.add(int[].class);
                        break;
                    case "long[]":
                        argTypes.add(long[].class);
                        break;
                    case "char[]":
                        argTypes.add(char[].class);
                        break;
                    case "float[]":
                        argTypes.add(float[].class);
                        break;
                    case "double[]":
                        argTypes.add(double[].class);
                        break;
                    case "boolean[]":
                        argTypes.add(boolean[].class);
                        break;
                    default:
                        if (argTypeName.endsWith("[]")) {
                            argTypes.add(Class.forName("[L" + argTypeName.substring(0,
                                    argTypeName.length() - 2) + ";"));
                        } else {
                            argTypes.add(Class.forName(argTypeName));
                        }
                        break;
                }
            }
        }

        Method origin = Class.forName(methodComponents.group(1)).getDeclaredMethod(
                methodComponents.group(2), argTypes.toArray(new Class<?>[]{}));

        if (isOverridden(instance, origin)) {
            return null;
        } else {
            return origin;
        }
    }
953571
public static Method bestMethod(Method[] methods, Class<?>[] argTypes) throws AmbiguousMethodMatchException {
        try {
            return best(methods, collectSignatures(methods), collectVarArgs(methods), argTypes);
        } catch (AmbiguousSignatureMatchException e) {
            throw new AmbiguousMethodMatchException(e, methods);
        }
    }
66716
private static <T> T createInstance(Constructor<T> constructor, Object... arguments) throws Exception {
        if (constructor == null) {
            throw new IllegalArgumentException("Constructor cannot be null");
        }
        constructor.setAccessible(true);

        T createdObject = null;
        try {
            if (constructor.isVarArgs()) {
                Class<?>[] parameterTypes = constructor.getParameterTypes();
                final int varArgsIndex = parameterTypes.length - 1;
                Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
                Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
                Object[] completeArgumentList = new Object[parameterTypes.length];
                System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
                completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
                createdObject = constructor.newInstance(completeArgumentList);
            } else {
                createdObject = constructor.newInstance(arguments);
            }
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof Exception) {
                throw (Exception) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            }
        }
        return createdObject;
    }
161730
public static Object createInstanceByType(Class<?> type, Object... args) throws Exception {
		if (args.length == 0) {
			Constructor<?> constructor = type.getConstructor();
			return constructor.newInstance();
		} else {
			throw new UnsupportedException(null, "NOT_SUPPORTED", "Constructors with parameters are not supported");
		}
	}
1212450
public static <T> MethodLiteral<T, Constructor<?>> get(Constructor<?> constructor,
      TypeLiteral<T> declaringType) {
    Preconditions.checkArgument(
        constructor.getDeclaringClass().equals(declaringType.getRawType()),
        "declaringType (%s) must be the type literal where constructor was declared (%s)!",
        declaringType, constructor.getDeclaringClass());
    return new ConstructorLiteral<T>(constructor, declaringType);
  }
539319
@SuppressWarnings("unchecked")
    private <T extends Assignable> Constructor<T> findConstructor(Class<T> extensionImplClass) {
        Constructor<?>[] constructors = SecurityActions.getConstructors(extensionImplClass);
        for (Constructor<?> constructor : constructors) {
            Class<?>[] parameters = constructor.getParameterTypes();
            if (parameters.length != 1) {
                continue;
            }
            Class<?> parameter = parameters[0];
            if (Archive.class.isAssignableFrom(parameter)) {
                return (Constructor<T>) constructor;
            }
        }
        throw new ExtensionLoadingException("No constructor with a single argument of type " + Archive.class.getName()
            + " could be found");
    }
1035804
public Expression construct(final Iterable<? extends Expression> args) {
    Expression.checkTypes(argTypes(), args);
    return new Expression(instanceClass().type(), Feature.NON_NULLABLE) {
      @Override
      protected void doGen(CodeBuilder mv) {
        mv.newInstance(instanceClass().type());
        // push a second reference onto the stack so there is still a reference to the new object
        // after invoking the constructor (constructors are void methods)
        mv.dup();
        for (Expression arg : args) {
          arg.gen(mv);
        }
        mv.invokeConstructor(instanceClass().type(), method());
      }
    };
  }
1374862
private <T> Constructor<T> findFromStringConstructorByType(Class<T> cls) {
        try {
            return cls.getDeclaredConstructor(String.class);
        } catch (NoSuchMethodException ex) {
            try {
                return cls.getDeclaredConstructor(CharSequence.class);
            } catch (NoSuchMethodException ex2) {
                throw new IllegalArgumentException("Constructor not found", ex2);
            }
        }
    }
598892
public static <T> Constructor<T> getConstructor(Class<T> instantiable, Class<?>... constructorParameterTypes)
    {
        try
        {
            return instantiable.getConstructor(constructorParameterTypes);
        }
        catch (NoSuchMethodException ignored)
        {
            return ReflectionHelper.searchForConstructor(instantiable, constructorParameterTypes);
        }
    }
480793
public static <T> Constructor<T>[] candidateConstructors(Class<T> clazz, Class<?>[] argTypes) {
        return candidateConstructors(collectConstructors(clazz), argTypes);
    }
1196595
public static <T> T[] candidates(T[] items, Class<?>[][] signatures, boolean[] varArgs, Class<?>[] argTypes) {
        final int[] indices = candidateMatches(signatures, varArgs, argTypes);
        T[] result = newArray(items.getClass().getComponentType(), indices.length);
        for (int i = 0; i < indices.length; i++) {
            result[i] = items[indices[i]];
        }
        return result;
    }
816691
public ASTConstructor getConstructor(Constructor constructor, boolean isEnum, boolean isInnerClass) {
        ASTAccessModifier modifier = ASTAccessModifier.getModifier(constructor.getModifiers());

        Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();

        if(constructor.getDeclaringClass().getEnclosingClass() != null && !Modifier.isStatic(constructor.getDeclaringClass().getModifiers())){
            // An inner class constructor contains a hidden non-annotated prameter
            Annotation[][] paddedParameterAnnotations = new Annotation[parameterAnnotations.length + 1][];

            paddedParameterAnnotations[0] = new Annotation[0];
            System.arraycopy(parameterAnnotations, 0, paddedParameterAnnotations, 1, parameterAnnotations.length);

            parameterAnnotations = paddedParameterAnnotations;
        }

        ImmutableList<ASTParameter> constructorParameters = getParameters(constructor.getParameterTypes(), constructor.getGenericParameterTypes(), parameterAnnotations);
        if(isEnum) {
            constructorParameters = constructorParameters.subList(2, constructorParameters.size());
        }
        if(isInnerClass){
            constructorParameters = constructorParameters.subList(1, constructorParameters.size());
        }
        ImmutableSet<ASTType> throwsTypes = getTypes(constructor.getExceptionTypes());

        return new ASTClassConstructor(getAnnotations(constructor), constructor, constructorParameters, modifier, throwsTypes);
    }
556543
public static Class<?>[] resolveArguments(Type genericType, Class<?> targetType) {
        Class<?>[] result = null;

        if (genericType instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) genericType;
            Type[] arguments = paramType.getActualTypeArguments();
            result = new Class[arguments.length];
            for (int i = 0; i < arguments.length; i++)
                result[i] = resolveClass(arguments[i], targetType);
        } else if (genericType instanceof TypeVariable) {
            result = new Class[1];
            result[0] = resolveClass(genericType, targetType);
        }

        return result;
    }