java - 如何使用groovy中的反射调用具有空参数值的方法?

标签 java reflection groovy

我使用 groovy 和 junit 来编写单元测试。我写了一个方法,testBrandIDParam ,测试一些常见的情况,例如 null参数值或paramID < 0使用反射。但是,当我测试null时param,这个方法并不总是有效。我该如何解决这个问题?

@Test
public void testGetDetailBrand() {
    GetDetailReqDTO reqDTO = new GetDetailReqDTO();
    testBrandIDParam(reqDTO, service, "getDetailBrand");
}

private <T> void testBrandIDParam(T requestDTO, Service service, String testMethod) {
    Class requestClazz = requestDTO.getClass();
    Class serviceClazz = service.getClass();
    java.lang.reflect.Method doTestMethod = serviceClazz.getMethod(testMethod, requestDTO.class);

    // test null
    CommonRespDTO respDTO = doTestMethod.invoke(service,{null });
    Assert.assertTrue(respDTO.getRespCode() == ICommonRespDTO.ResponseCode.FAIL.getCode());

    T reqInstance = (T) requestClazz.newInstance();
    // req-ID = 0
    respDTO = (CommonRespDTO) doTestMethod.invoke(service, reqInstance)
    Assert.assertTrue(!respDTO.isSuccess());

    brandIDField.setAccessible(false);
}

注:getDetailBrand()只有一个参数,brandID .

  1. CommonRespDTO respDTO = doTestMethod.invoke(service,{null });
    抛出

    java.lang.IllegalArgumentException: argument type mismatch

  2. CommonRespDTO respDTO = doTestMethod.invoke(service,new Object[1]{ null });
    抛出

    groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.Object;.call() is applicable for argument types: (service.serviceTest$_testBrandIDParam_closure1) values: [service.serviceTest$_testBrandIDParam_closure1@28236ebc]
    Possible solutions: tail(), wait(), any(), max(), last(), wait(long)

  3. CommonRespDTO respDTO = doTestMethod.invoke(service,new Object[1]{ null });
    产生编译错误:

    new Objecy[] cannot be applied to groovy.lang.Closure

最佳答案

您需要将Object数组传递给invoke()。这有点棘手:

doTestMethod.invoke(service, [null] as Object[])

关于java - 如何使用groovy中的反射调用具有空参数值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37698215/

相关文章:

java:netbeans gui 按钮不能同时工作

java - 反射获取特定类中带注释的所有方法

groovy - 在 Netbeans 中运行 fork 的 groovyc 时出错

groovy - Groovy 中的元对象协议(protocol) (MOP)

gradle - Gradle的Groovy语法:项目

java - 改造 JSON 反序列化对象的 $ref 对其原始副本的引用

java - 如何从 map 中的集合中删除元素

java - Clojure,反射 : Find classes that implement an interface

具有通用类类型的 Java 反射 getDeclaredMethod()

java - 原型(prototype)设计模式Java实现困惑