Java 反射 getDeclaredMethod 抛出 NoSuchMethodException

标签 java reflection

我在类 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/

相关文章:

java - 使用动态字段反序列化嵌套 XML

c# - 获取 Action 名称作为属性参数的字符串

Ruby:如何获取可选 proc 参数的默认值

java - 将字段值设置为同一类的另一个实例

java - 请解释 Java 内存模型中阐明的初始化安全性

java - 为什么我们要在 Java 中以 Object 作为参数编写 equals 方法?

java - 我怎样才能只用一个事件来收听我的所有组件?

java - 计算每个字母在文件中出现的次数

java - Class.getMethod() 反射和自动装箱的任何解决方案?

asp.net-mvc - 为什么在 ASP.NET MVC 中使用 lambdas 而不是反射?