我在类 SonarRestApiServiceImpl
中声明了一个私有(private)方法 getListSonarMetricsFromRegistry
,我想使用 Java 反射调用该方法,但出现异常:
<小时/>java.lang.NoSuchMethodException: com.cma.kpibatch.rest.impl.SonarRestApiServiceImpl.getListSonarMetricsFromRegistry(java.util.HashMap)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at com.test.service.rest.SonarRestApiServiceImplTest.testGetListSonarMetricsFromRegistry(SonarRestApiServiceImplTest.java:81)
我尝试使用 Java 反射,如下所示:
@Test
public void initTest() throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Map<Long, KpiMetric> tmp = new HashMap<>();
Method method = sonarRestApi.getClass().getDeclaredMethod("getListSonarMetricsFromRegistry", tmp.getClass());
method.setAccessible(true);
List<String> list = (List<String>) method.invoke(sonarRestApi, registry.getKpiMetricMap());
}
这是 getListSonarMetricsFromRegistry
方法声明:
//This method works correctly, it returns a List of String without error
private List<String> getListSonarMetricsFromRegistry(Map<Long, KpiMetric> map) {
return //something
}
<小时/>
当我查看异常时,跟踪会使用正确的包、正确的名称、正确的方法名称和正确的参数打印我的类:
com.test.rest.impl.SonarRestApiServiceImpl.getListSonarMetricsFromRegistry(java.util.HashMap) But it say that this method does not exist, which is strange.
Stackoverflow 提供的类似问题确实有帮助,但我仍然有相同的异常。
最佳答案
我认为你的问题是你给出了 HashMap
类实例作为 getDeclaredMethod
的参数而该方法实际上接受 Map
类实例。请记住,所有通用参数都会在编译时被删除,因此 Map<Whatever,WhateverElse>
简单地变成 Map
在运行时进行反射时。所以尝试一下:
Method method = sonarRestApi.getClass().getDeclaredMethod("getListSonarMetricsFromRegistry", Map.class);
与此相关的是,从长远来看,基于反射调用私有(private) API 的测试可能不是保持测试可维护的好方法。我不确定您为什么需要这样做,但如果可以的话,请尝试找到一种适用于公共(public) API 的方法。
关于Java 反射 getDeclaredMethod 抛出 NoSuchMethodException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57672156/