What is NoSuchMethodException in Java and when does it occurs?
Answers
Explanation:
I hope it is helpful .
mark me as brainlist .
A NoSuchMethodError occurs when we’re calling a method that does not exist at runtime.
The method must have existed at compile time, since otherwise the compiler would have refused to compile the class calling that method with an error: cannot find symbol.
Some common situations that cause a NoSuchMethodError-
1) Breaking Change in a 3rd Party Library-
The potential root cause for a NoSuchMethodError is that one of the libraries we use in our project had a breaking change from one version to the next. This breaking change removed a method from the c.ode of that library.
However, since our own co.de calling the method in question has been successfully compiled, the classpath must be different during compile time and runtime.
At compile time we use the correct version of the library while at runtime we somehow included a different version that does not provide the method in question. This indicates a problem in our build process.
2) Overriding a 3rd Party Library Version-
Imagine we’re using a 3rd party library (A) as described above, but we’re not calling it directly. Rather, it’s a dependency of another 3rd party library (B) that we use (i.e. A is a transitive dependency to our project).
In this case, which is the most common cause for NoSuchMethodErrors in my experience, we probably have a version conflict in our build system.
There probably is a third library (C) which also has a dependency on B, but on a different version.Building systems like Gradle and Maven usually resolve a version conflict like this by simply choosing one of the versions, opening the door for a NoSuchMethodError.
3) Breaking Change in Our Own Module-
The same can happen in multi-module builds, though this is less common. We have removed a certain method from the co.de in one module (A) and during runtime the cod.e of another module (B) fails with a NoSuchMethodError.
This indicates an error in our build pipeline since module B obviously has not been compiled against the new version of module A.