通过将运行时参数传递给java reflect方法进行单元测试

通过将运行时参数传递给java reflect方法进行单元测试,java,unit-testing,methods,Java,Unit Testing,Methods,我正在代码中使用JavaBean创建一个类对象。然后我调用该类的一个特定方法obj public static void runUnitTest(String className, String methodName, List<Object> inputParams, Object expectedReturnValue){ try { // Make the class object to be tested on

我正在代码中使用JavaBean创建一个类对象。然后我调用该类的一个特定方法obj

public static void runUnitTest(String className, String methodName, List<Object> inputParams, Object expectedReturnValue){
                try {
        // Make the class object to be tested on
        Object classObj = Class.forName(className).newInstance();
        Method calledMethod = classObj.getClass().getMethod(methodName,inputParams.get(0).getClass());
        Object returnVal = calledMethod.invoke(classObj,inputParams.get(0));
        }catch (InstantiationException | IllegalAccessException
                        | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
    }
这很好,因为我知道方法
getOutputNumber
只有一个参数。但是当我必须为参数数量不同的多个方法调用相同的代码时(例如,
getAdditionalOutputNumber
),我不能使用相同的代码。我不想根据inputParams的大小使用multipleif-else或case块。 是否有一种通用的方法来调用以下内容:

Method calledMethod = classObj.getClass().getMethod(methodName,**?? What to pass here ??**);
Object returnVal = calledMethod.invoke(classObj,**?? What to pass here ??**);

您只需要从参数列表中构建合适的数组来调用反射API

Class[] types = new Class[inputParams.size()];
int i = 0;
for(Object param:inputParams) {
    types[i++] = param.getClass();
}
Method calledMethod = classObj.getClass().getMethod(methodName,types);
Object returnVal = calledMethod.invoke(classObj,inputParams.toArray());

原语类型和空值可能存在一些问题。

@RC。不管怎样,我都会把代码和框架结合起来。尽管如此,如果你在阅读完问题后提出建议会更好。当然,让我把它收回。你能详细说明一下吗?太棒了。。这正是我想要的。非常感谢。
Method calledMethod = classObj.getClass().getMethod(methodName,**?? What to pass here ??**);
Object returnVal = calledMethod.invoke(classObj,**?? What to pass here ??**);
Class[] types = new Class[inputParams.size()];
int i = 0;
for(Object param:inputParams) {
    types[i++] = param.getClass();
}
Method calledMethod = classObj.getClass().getMethod(methodName,types);
Object returnVal = calledMethod.invoke(classObj,inputParams.toArray());