How do I fix a NoSuchMethodError?

2018-12-31 01:41发布

I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it?

25条回答
心情的温度
2楼-- · 2018-12-31 02:25

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.

查看更多
荒废的爱情
3楼-- · 2018-12-31 02:25

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.

DISP_E_EXCEPTION [step] [] [Z-JAVA-105 Java exception java.lang.NoSuchMethodError(com.example.yourmethod)]

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 02:26

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

查看更多
公子世无双
5楼-- · 2018-12-31 02:28

Note that in the case of reflection, you get an NoSuchMethodException, while with non-reflective code, you get NoSuchMethodError. I tend to go looking in very different places when confronted with one versus the other.

查看更多
浮光初槿花落
6楼-- · 2018-12-31 02:29

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 the getDeclaredMethod call will throw a NoSuchMethodException.

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.)

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 02:32

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.

查看更多
登录 后发表回答