简体   繁体   中英

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

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.

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

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-KV-

It says:

Since: 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM