0
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]

My JDK version is 1.7.0_80. The error message will happen again when I execute the following JUnit test code:

@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!");

}
3
  • Why should there be such a constructor? What are you trying to do? HashMap$EntrySet is not part of any public API so any methods that it does or does not have (outside of the interfaces that it exposes) are implementation details that you should not depend on. Commented Mar 11, 2019 at 9:31
  • What is the purpose of that test scenario? Also, please be aware that Map.Entry is an interface. Interfaces does not have any constructors. Commented Mar 11, 2019 at 9:34
  • 1
    Thanks for your replying.You are right, EntrySet is an inner class in java.util.HashMap which owns private final mofifiers. Why I ask this question,because I encounter such code in a colleague 's deepClone() method which throws such exception. Commented Mar 11, 2019 at 9:38

2 Answers 2

3

You can get the answer by listing the declared constructors .

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)

So, there is one constructor, which takes a HashMap as argment. Hence, getDeclaredConstructor(), (getDeclaredConstructor(Class<?>... parameterTypes) with no args) tries to get a constructor that does not exist.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm no expert on reflection but to me that sounds like there is no default constructor in the class of the entrySet. And with getDeclaredConstructor() that's what you're looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.