package SalesUnitsIntoCarton.mySolution;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class UtilityReflections {
private static final Object[] EMPTY = {};
/**
* This method returns a value, returned by the method of a private inner class, of a given object instance.
*
* @param outerClassInstance This parameter needs to be an instance of the outer class that contains the private inner class.
* @param attributeNameOfInnerClassInOuterClass This is the name of the attribute that is an inner class type, within the outer class.
* @param innerClassName This is the class name of the inner class.
* @param methodNameOfInnerClass This is the name of the method inside the inner class that should be called.
* @return Returns the value returned by the method of the inner class. CAUTION: needs casting since its of type {@link Object}
*
* @throws SecurityException
* @throws NoSuchFieldException
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws Exception
*/
public static <T extends Object> Object executeInnerClassMethod(T outerClassInstance, String attributeNameOfInnerClassInOuterClass, String innerClassName, String methodNameOfInnerClass)
throws NoSuchFieldException, SecurityException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
final Class<?> outerClass = outerClassInstance.getClass();
final Field field = outerClass.getDeclaredField(attributeNameOfInnerClassInOuterClass);
field.setAccessible(true);
Class<?> innerClass = Class.forName(innerClassName);
innerClass = field.getType();
//access the method
final Method method = innerClass.getDeclaredMethod(methodName, new Class<?>[]{});
method.setAccessible(true);
return method.invoke(field.get(outerClassInstance), EMPTY);
}
}
"테스트 동작, 구현 아님". 이것이 개인 내부 클래스 인 경우 구현 세부 사항입니다. 클래스의 동작 (public 메서드를 통해 노출)에 대해 생각하고 테스트합니다. –
이 구현 세부 사항을 테스트해야합니다. 이것은 단위 테스트입니다. – user1918858
@ JaroslawPawlak의 의견과 비슷하게 특정 동작을 가장 잘 테스트하는 경우 테스트 할 수있는 공용 메서드를 사용하여이 동작을 다른 개체로 리팩토링하는 것이 좋습니다. 그런 다음 이러한 개인 메서드가있는 기존 개체는 테스트 된 공용 동작과 함께이 새 개체를 내부적으로 사용할 수 있습니다. – FishStix