java - 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 提供的类似问题确实有帮助,但我仍然有同样的异常。
解决方案
我认为你的问题是你给了一个HashMap
类实例作为参数,getDeclaredMethod
而该方法实际上接受了Map
类实例。请记住,所有泛型参数都在编译时被剥离,因此在运行时进行反射时aMap<Whatever,WhateverElse>
简单地变成了 a 。Map
所以试试:
Method method = sonarRestApi.getClass().getDeclaredMethod("getListSonarMetricsFromRegistry", Map.class);
在相关的说明中,基于反射调用私有 API 的测试可能不是长期保持测试可维护性的好方法。我不确定您为什么需要这样做,但如果可以,请尝试找到一种适用于公共 API 的方法。
推荐阅读
- google-bigquery - 用 java 覆盖 BigQuery 中的表
- python-3.6 - Unexpected IndentationError - 为什么?
- javascript - 无法为 Chrome 中的日期输入赋值
- json - 尝试使用 json API 时出现 React JS - 404 - (Not Found) 错误
- python - Python:拆分文本/xml;charset=UTF-8
- twilio - 使用 Twilio 可编程聊天 REST API 获取用户私人频道列表
- javascript - 只选择一个具有多个类的元素?
- typescript - 如何使用 [key: string] 从 Typescript 类型中删除字段:任何
- jsreport - jsreport“报告器初始化期间发生错误”
- jasmine - 将 jasmine-jquery 与 Jest 一起使用