I have a private method getListSonarMetricsFromRegistry declared in the Class SonarRestApiServiceImpl that I want to call, with Java reflection, but I get the exception:
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)
I tried to use Java reflection, like below :
@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());
}
Here is the getListSonarMetricsFromRegistry method declaration:
//This method works correctly, it returns a List of String without error
private List<String> getListSonarMetricsFromRegistry(Map<Long, KpiMetric> map) {
return //something
}
When I look at the Exception, the trace print my Class with the right package, right name, right method name and right parameters:
com.test.rest.impl.SonarRestApiServiceImpl.getListSonarMetricsFromRegistry(java.util.HashMap) But it say that this method does not exist, which is strange.
The similar questions provided by Stackoverflow did help, but I still have the same Exception.
HashMapis not the same asMap- one is theinterfacethe other the implementation. Your call togetDeclaredMethodusestmp.getClasswhich will returnHasMap.classand your method takes aMap. You need to call withMap.class.