I'm getting a NoSuchMethodError
error when running my Java program. What's wrong and how do I fix it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
If using maven or another framework, and you get this error randomly almost, try "clean install", especially if you wrote the object and you know it has the method. Worked for me.
I've had the same problem. This is also caused when there is an ambiguity in classes. My program was trying to invoke a method which was present in two JAR files present in the same location / class path. Delete one JAR file or execute your code such that only one JAR file is used. Check that you are not using same JAR or different versions of the same JAR that contain the same class.
For me it happened because I changed argument type in function, from Object a, to String a. I could resolve it with clean and build again
Note that in the case of reflection, you get an
NoSuchMethodException
, while with non-reflective code, you getNoSuchMethodError
. I tend to go looking in very different places when confronted with one versus the other.This can also be the result of using reflection. If you have code that reflects on a class and extracts a method by name (eg: with
Class.getDeclaredMethod("someMethodName", .....)
) then any time that method name changes, such as during a refactor, you will need to remember to update the parameters to the reflection method to match the new method signature, or thegetDeclaredMethod
call will throw aNoSuchMethodException
.If this is the reason, then the stack trace should show the point that the reflection method is invoked, and you'll just need to update the parameters to match the actual method signature.
In my experience, this comes up occasionally when unit testing private methods/fields, and using a
TestUtilities
class to extract fields for test verification. (Generally with legacy code that wasn't designed with unit testing in mind.)This is usually caused when using a build system like Apache Ant that only compiles java files when the java file is newer than the class file. If a method signature changes and classes were using the old version things may not be compiled correctly. The usual fix is to do a full rebuild (usually "ant clean" then "ant").
Sometimes this can also be caused when compiling against one version of a library but running against a different version.