Java反射getDeclaredMethod引发NoSuchMethodException

Java反射getDeclaredMethod引发NoSuchMethodException,java,reflection,Java,Reflection,我有一个私有方法getListSonarMetricsFromRegistry,它是在我想要调用的SonarRestApiServiceImpl类中声明的,带有Java反射,但是我得到了一个异常: java.lang.NoSuchMethodException:com.cma.kpibatch.rest.impl.SonaRestapiServiceImpl.GetListSonaMetricsFromRegistryJava.util.HashMap 位于java.lang.Class.get

我有一个私有方法getListSonarMetricsFromRegistry,它是在我想要调用的SonarRestApiServiceImpl类中声明的,带有Java反射,但是我得到了一个异常:

java.lang.NoSuchMethodException:com.cma.kpibatch.rest.impl.SonaRestapiServiceImpl.GetListSonaMetricsFromRegistryJava.util.HashMap 位于java.lang.Class.getDeclaredMethodClass.java:2130 位于com.test.service.rest.SonarRestApiServiceImplTest.testGetListSonarMetricsFromRegistrySonarRestApiServiceImplTest.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());
    }

当我查看异常时,跟踪将使用正确的包、正确的名称、正确的方法名称和正确的参数打印我的类:

com.test.rest.impl.sonarrestapiservice.getListSonaMetricsFromRegistryJava.util.HashMap 但它说这种方法不存在,这很奇怪


Stackoverflow提供的类似问题确实有帮助,但我仍然有相同的例外。

我认为您的问题是,您将一个HashMap类实例作为getDeclaredMethod的参数,而该方法实际上接受Map类实例。请记住,所有泛型参数都是在编译时剥离出来的,所以在运行时进行反射时,映射只是简单地变成映射。因此,请尝试:

方法Method=sonarRestApi.getClass.getDeclaredMethodGetListSonaMetricsFromRegistry,Map.class;
另一方面,基于反射调用私有API的测试可能不是保持测试长期可维护性的好方法。我不确定您为什么需要这样做,但如果可以的话,请尝试找到一种使用公共API的方法。

HashMap与Map不同-一个是接口,另一个是实现。对getDeclaredMethod的调用使用tmp.getClass,它将返回HasMap.class,并且您的方法将获取一个映射。你需要打电话给Map.class。事实上,这解决了问题,你对我正在做的事情也是正确的,作为一个诡计,我会看看我是否能找到另一种方法,谢谢你的帮助
//This method works correctly, it returns a List of String without error
private List<String> getListSonarMetricsFromRegistry(Map<Long, KpiMetric> map) {
    return //something
}