/** * Finds and returns a certain constructor. If the constructor couldn't be * found this method delegates to * * @param type The type where the constructor should be located. * @param arguments The arguments passed to the constructor. * @return The found constructor. * @throws ConstructorNotFoundException if no constructor was found. * @throws TooManyConstructorsFoundException if too constructors matched. * @throws IllegalArgumentException if {@code type} is null. */ public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) { return new ConstructorFinder(type, arguments).findConstructor(); }
private void lookupPotentialConstructor() {Set<Constructor> constructors = getDeclaredConstructorsWithoutPowerMockConstructor(); for (Constructor constructor : constructors) { if (constructor.canBeInvokeWith(arguments)) { setPotentialConstructor(constructor); } // if a constructor is found and it has varargs parameters then the constructor will be used even if // other constructor is matcher the given arguments. It is done, because when Argument Matchers are used // arguments passed to the method are null value and it's imposable to determinate whether parameters // match to arguments or not. if (isVarArgConstructorFound()){ return; } } }
public java.lang.reflect.Constructor findConstructor() { lookupPotentialConstructor(); throwExceptionIfConstructorWasNotFound(); return potentialConstructor.getJavaConstructor(); }
ConstructorFinder(Class<?> type, Object... arguments) { if (type == null) { throw new IllegalArgumentException("Class type cannot be null."); } this.type = type; this.arguments = arguments; this.unmockedType = WhiteboxImpl.getOriginalUnmockedType(type); if (isNestedClass() && arguments != null) { addArgumentForNestedClass(); } }
private Set<Constructor> getDeclaredConstructorsWithoutPowerMockConstructor() { Set<Constructor> constructors = new HashSet<Constructor>(); for (java.lang.reflect.Constructor<?> constructor : unmockedType.getDeclaredConstructors()) { if (!isPowerMockConstructor(constructor.getParameterTypes())) { constructors.add(new Constructor(constructor)); } } return constructors; }