首页 > 解决方案 > Java反射getDeclaredMethod抛出NoSuchMethodException

问题描述

我在要调用getListSonarMetricsFromRegistry的类中声明了一个私有方法,使用 Java 反射,但出现异常:SonarRestApiServiceImpl


java.lang.NoSuchMethodException:com.test.service.rest处的 java.lang.Class.getDeclaredMethod(Class.java:2130) 处的com.cma.kpibatch.rest.impl.SonarRestApiServiceImpl.getListSonarMetricsFromRegistry(java.util.HashMap)
。 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) 但是说这个方法不存在,很奇怪。

Stackoverflow 提供的类似问题确实有帮助,但我仍然有同样的异常。

标签: javareflection

解决方案


我认为你的问题是你给了一个HashMap类实例作为参数,getDeclaredMethod而该方法实际上接受了Map类实例。请记住,所有泛型参数都在编译时被剥离,因此在运行时进行反射时aMap<Whatever,WhateverElse>简单地变成了 a 。Map所以试试:

 Method method = sonarRestApi.getClass().getDeclaredMethod("getListSonarMetricsFromRegistry", Map.class);

在相关的说明中,基于反射调用私有 API 的测试可能不是长期保持测试可维护性的好方法。我不确定您为什么需要这样做,但如果可以,请尝试找到一种适用于公共 API 的方法。


推荐阅读