NoSuchMethodError exception when using com.google.

2020-04-01 12:07发布

I'm trying to use com.google.common.base.Splitter as follows

Iterable<String> segs = Splitter.on("/").split("one/two/three/four/five");

for (String seg : segs) {
  System.out.println(seg);
}

However, I'm seeing the following exception:

Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Platform.precomputeCharMatcher(Lcom/google/common/base/CharMatcher;)Lcom/google/common/base/CharMatcher;
    at com.google.common.base.CharMatcher.precomputed(CharMatcher.java:664)
    at com.google.common.base.CharMatcher.<clinit>(CharMatcher.java:71)
    at com.google.common.base.Splitter.<init>(Splitter.java:107)
    at com.google.common.base.Splitter.on(Splitter.java:171)
    at Test.main(Test.java:30)

Does anyone have any idea what I'm doing wrong here?

7条回答
Evening l夕情丶
2楼-- · 2020-04-01 12:43

I encountered the same problem. It turned out that I used a older version of guava. Go to this website:https://code.google.com/p/guava-libraries/, and download a newer version.

By the way,google-collections was renamed to Guava.

查看更多
闹够了就滚
3楼-- · 2020-04-01 12:43

Another reason this happens is if the GSON library is imported before the Guava library.

See: https://github.com/google/guava/issues/2786

I was importing the jars from a folder into IntelliJ. What ended up working was add a "z" next to gson (so the jar would be named zgson) so that Guava would import first.

查看更多
forever°为你锁心
4楼-- · 2020-04-01 12:43

For me this happens when you have a dependency which depends on an earlier version of Guava, and this dependency is listed first. Guava will be resolved at the place it was found first and ignore the rest.

The fix is to add the dependency on guava first, but careful that it does not break other projects which use guava

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-04-01 12:53

Yeah, It's the problem with guava library only. Keep the updated library and remove all remaining versions of guava if you have any and try. Should work fine.

查看更多
做个烂人
6楼-- · 2020-04-01 12:56

Your problem is that another library might also contain a guava library and it's being loaded first from your classpath instead of the version you want. This would cause this runtime exception.

查看更多
Luminary・发光体
7楼-- · 2020-04-01 12:58

Use the below dependency to fix the issue

To add a dependency on Guava using Maven, use the following:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>19.0</version>
</dependency>

To add a dependency using Gradle:

dependencies {
  compile 'com.google.guava:guava:19.0'
}
查看更多
登录 后发表回答