In this post, we are going to see the
NoSuchMethodError error that we get at runtime when there’s a dependency conflict in our Java Maven application and we will see how can we overcome this error by fixing the dependency in our
Why we get this error?
When we have two different
jars of the same library that have the same class in different packages and one method of this class is called by the application in execution time the JVM throws a
In the picture above we have two different versions of Guava (16 and 25.1-android) that have the same class
According to the Oracle documentation, this error may occur at runtime if a class has been incompatibly changed.
In the following example we will see a problem that I had with transitive dependencies (the ones that we import into our application indirectly from other dependencies)
A real example
In the following image we can see that the call to the method
checkArgument of the class
PreConditions of Guava library threw
If we look for the class
PreConditions in Intellij Idea typing
PreConditions.class in the search menu (if we don’t write .class in Intellij we won’t find the class) we will see that it’s present in three different
- Guava version 25.1-android
- Guava version 16.0
- rt.jar 1.8
Looking at the dependencies
We can check the maven dependencies tree using the maven dependency plugin in the command line
$> mvn dependency:tree
or using the dependency view diagram with the Intellij Idea:
In this case, we can see the red lines that indicate we have a dependency conflict.
How to fix it
We need to set up one of the two versions in the
dependency management section in our
pom.xml (parent if we have a multi-module project)
After setting the dependency in the pom file If we come back to the dependency tree we won’t see red lines anymore, neither in the maven dependency plugin.
In this post, we have seen how to fix the
NoSuchMethodError and the reason why it’s thrown in our Java Maven application.
If you want more information regarding how to manage Maven dependencies you can read this post that I wrote some time ago.