首页 > 解决方案 > java.lang.NoSuchMethodException:java.util.HashMap$EntrySet。()

问题描述

Caused by: java.lang.NoSuchMethodException: java.util.HashMap$EntrySet.<init>()

at java.lang.Class.getConstructor0(Class.java:2902) ~[na:1.7.0_80]
at java.lang.Class.getDeclaredConstructor(Class.java:2066) ~[na:1.7.0_80]

我的 JDK 版本是 1.7.0_80。当我执行以下 JUnit 测试代码时,错误消息将再次出现:

@Test
public void testGetDeclaredConstructor() throws NoSuchMethodException {
    Map<String, Object> m1 = new HashMap<>();
    Set<Map.Entry<String, Object>> entrySet = m1.entrySet();

    Class clz = entrySet.getClass();

    Constructor con = clz.getDeclaredConstructor();
    con.setAccessible(true);

    System.out.println("--------Test OK!");

}

标签: java

解决方案


您可以通过列出声明的构造函数来得到答案。

Set<Map.Entry<Object, Object>> entrySet = new HashMap<>().entrySet();

Constructor<?>[] declaredConstructors = entrySet.getClass().getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
    System.out.println(declaredConstructor);
}

java.util.HashMap$EntrySet(java.util.HashMap)

因此,有一个构造函数,它以 HashMap 作为参数。因此,getDeclaredConstructor(), (getDeclaredConstructor(Class<?>... parameterTypes)没有参数) 试图获取一个不存在的构造函数。


推荐阅读