0

Trying to unit test a class which builds a static map within a class as follows:

private static Map<String, SomeClass> MAP = new HashMap<>();
static {
    MAP = Map.ofEntries(
              Map.entry(SOME_KEY, new SomeClass()),
               .
               .
               .
              Map.entry(SOME_KEY, new SomeClass())
          );
}

When the map is being initialized during construction of the class I am getting the following error:

java.lang.NoSuchMethodError: java.util.Map.entry(Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/Map$Entry;

at package.ClassContainingMap.<clinit>(ClassContainingMap.java:36).

I have seen a similar post post on troubleshooting this error at How do I fix a NoSuchMethodError? and have tried cleaning and rebuilding as suggested in one place, but to no avail. The accepted response suggests that perhaps a separate library versions might be being used to compile and run the code, but I have no idea how to figure that out as I am relatively new to Android and Java development. I should note that the application is being built using desugaring to allow use of some newer functionality and am not sure if this may be related to that in some capacity?

Thanks in advance.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
dan
  • 1
  • 1

2 Answers2

1

It seems to be related to desugaring. The Map.entry() methos is nor available in Java 8 and 7, which is used by Android.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
  • Correct me if I am wrong, but if it is in the documentation for Java Platform SE 7 that means it is a part of Java 7?https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html – dan Apr 02 '21 at 20:06
  • 2
    That's the class `Map.Entry`, not the static method `Map.entry()`. You can see the documentation for the *method* in the [documentation](https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#entry-K-V-). – Henry Twist Apr 02 '21 at 20:13
0

NoSuchMethod error tells you that the method doesn't exists. This usually means that you are using the wrong version of a library at runtime.

This happens when your working environment is not aligned with the environment where your application runs. In this case, if you work with the same libraries you have at runtime, your project won't compile.

Because this is a method in the JDK and it has been introduced since JDK 9, if you are using an earlier version of the jdk to run your code, it's not going to work.

See the javadoc: https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#entry-K-V-

It says:

Since: 9

Davide D'Alto
  • 7,421
  • 2
  • 16
  • 30