Как исправить ошибку java.lang.NoSuchMethodError?

Ошибка java.lang.NoSuchMethodError на Java выдается, когда программа пытается вызвать метод класса, который не существует. Метод может быть статическим или также может быть методом экземпляра.
В большинстве случаев java.lang.NoSuchMethodError перехватывается компилятором, но иногда это может происходить во время выполнения. Если эта ошибка возникает во время выполнения, то единственной причиной может быть изменение структуры класса, которое сделало ее несовместимой.
Давайте разберем подробнее как исправить ошибку, у нас есть два класса Data и Temp, как показано ниже.
Давайте запустим их через командную строку. Обратите внимание, что я не использую Eclipse или какую-либо другую IDE, чтобы избежать обнаружения этой ошибки во время компиляции.
pankaj:Downloads pankaj$ javac Data.java
pankaj:Downloads pankaj$ javac Temp.java
pankaj:Downloads pankaj$ java Temp
foo
bar
pankaj:Downloads pankaj$
Итак, программа выполнена, давайте продолжим и изменим определение класса данных, как показано ниже.
Обратите внимание, что я удалил метод bar(). Теперь нам нужно будет скомпилировать только класс данных, а не основной класс.
Мы получили ошибку java.lang.NoSuchMethodError, потому что класс Data стал несовместим с классом Temp. Если бы мы попытались скомпилировать класс Data, мы получили бы ошибку, как показано ниже.
Есть две основные причины:
- Версия Jar, используемая во время компиляции, отличается от версии среды выполнения. Например, у вас мог бы быть MySQL jar в вашем приложении, имеющим другую версию от того, что присутствует в папке lib Tomcat. Поскольку Tomcat lib folder jars сначала просматривается Java Classloader, тогда возможна эта ошибка, если какой-либо метод не найден в загруженном классе.
- Конфликт из-за того же имени класса. Например, приложение использует сторонний jar-файл с таким же полным именем класса, как у вас. Поэтому, если classloader загружает класс из другого jar.
Отладка java.lang.NoSuchMethodError
Вы можете использовать java runtime option-verbose:class, чтобы получить информацию о jar, который используется для загрузки класса. Эту конфигурацию можно задать в tomcat catalina.sh или setenv.sh.
JAVA_OPTS=»$JAVA_OPTS -verbose:class»
Затем вы увидите логи, подобные приведенным ниже, которые очень полезны для выяснения фактического jar-файла, используемого при загрузке класса, и причины java.lang.NoSuchMethodError во время выполнения.
Средняя оценка 2 / 5. Количество голосов: 12
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Или поделись статьей
Видим, что вы не нашли ответ на свой вопрос.
Помогите улучшить статью.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.
How to Fix java.lang.NoSuchMethodError in Java

A java.lang.NoSuchMethodError is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java.lang.OutOfMemoryError . This error can also be thrown when the native memory is insufficient to support the loading of a Java class.
What Causes java.lang.NoSuchMethodError
The java.lang.NoSuchMethodError occurs when an application does not find a called method at runtime. Some of the most common causes for a java.lang.NoSuchMethodError are:
Breaking change in an third party library
If an application calls a method in a third party library, which exists at compile time but not at runtime, it can cause a java.lang.NoSuchMethodError . The third party library may have introduced a breaking change from one version to another — for example, it may have removed the method being called.
This usually indicates a problem with the build, since the method does exist at compile time but not at runtime. The version of the library used in the build may be different from the one used in the application code.
Breaking change within an application
A change in the class structure within an application can also cause a java.lang.NoSuchMethodError . This can happen in a multi-module application where a method may have been removed from the code in one module, which was called by another module.
This also indicates a problem with the build process, which may be referring to a different version of the called module.
Overriding third party library version
This can happen in case a third party library is used in an application, but not directly. For example, it could be a dependency of other third party libraries in the application, but which use different versions of the called library.
This can lead to a version conflict, resulting in a java.lang.NoSuchMethodError. Using build tools like Apache Maven and Gradle can prevent these kinds of version conflicts with their dependency management capabilities.
java.lang.NoSuchMethodError Example
Here is an example of java.lang.NoSuchMethodError thrown due to a breaking change introduced within an application.
Two classes will be created for this, the first of which is NoSuchMethodErrorExample which contains a method called print():
The second class Main calls the print() method from NoSuchMethodErrorExample :
When the Main class is executed, it produces the following output as expected:
Now if the print() method is removed from the NoSuchMethodErrorExample class and only this class is recompiled, when the Main class is executed again, it throws a java.lang.NoSuchMethodError :
The java.lang.NoSuchMethodError is thrown because the print() method is not found at runtime.
How to fix the java.lang.NoSuchMethodError
1. Full clean and compile
If a java.lang.NoSuchMethodError is encountered due to a breaking change within an application, a full clean and re-compilation of the project(s) containing both the calling and called classes should be performed. This will help make sure that the latest versions of the classes are used and resolve any inconsistencies.
2. Resolve third party library versioning issues
If a java.lang.NoSuchMethodError comes from calling a third party library method, finding out which library contains the called class and method can help detect inconsistent versioning between compile time and runtime dependencies.
The Java runtime option -verbose:class can be used to obtain information about the libraries used to load the called class. As an example, running the -verbose:class can produce the following output:
Examining the output can help figure out the version of the libraries used at runtime and resolve any inconsistencies.
Track, Analyze and Manage Java Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.
«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»
How do I fix a NoSuchMethodError?
I’m getting a NoSuchMethodError error when running my Java program. What’s wrong and how do I fix it?
32 Answers 32
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it.
Look at the stack trace . If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places.
If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.
I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn’t done the last one by dragging the «.jar» file direct from the file system into the «lib» folder on my eclipse project. Additionally, I had to remove the previous version of the library from both the build path and the «lib» folder.
Step 1 — Add .jar to build path
Step 2 — Associate sources and javadocs (optional)
Step 3 — Actually drag .jar file into «lib» folder (not optional)
![]()
![]()
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.
If you have access to change the JVM parameters, adding verbose output should allow you to see what classes are being loaded from which JAR files.
When your program is run, the JVM should dump to standard out information such as:
.
[Loaded junit.framework.Assert from file:/C:/Program%20Files/junit3.8.2/junit.jar]
.
If using Maven or another framework, and you get this error almost randomly, try a clean install like.
This is especially likely to work if you wrote the object and you know it has the method.
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.
I had the same error:
To solve it I checked, firstly, Module Dependency Diagram ( click in your POM the combination -> Ctrl+Alt+Shift+U or right click in your POM -> Maven -> Show dependencies ) to understand where exactly was the conflict between libraries (Intelij IDEA). In my particular case, I had different versions of Jackson dependencies.

1) So, I added directly in my POM of the project explicitly the highest version — 2.8.7 of these two.
And as dependency:
2) But also it can be solved using Dependency Exclusions.
By the same principle as below in example:
Dependency with unwanted version will be excluded from your project.
![]()
Why anybody doesn’t mention dependency conflicts? This common problem can be related to included dependency jars with different versions. Detailed explanation and solution: https://dzone.com/articles/solving-dependency-conflicts-in-maven
Add this maven dependency;
Then run this command;
Maybe this is the cause your the issue you faced.
![]()
If you are writing a webapp, ensure that you don’t have conflicting versions of a jar in your container’s global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.
- tomcat/common/lib
- mywebapp/WEB-INF/lib
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
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.)
In my case I had a multi module project and scenario was like com.xyz.TestClass was in module A and as well as in module B and module A was dependent on module B . So while creating a assembly jar I think only one version of class was retained if that doesn’t have the invoked method then I was getting NoSuchMethodError runtime exception, but compilation was fine.
![]()
It means the respective method is not present in the class:
- If you are using jar then decompile and check if the respective version of jar have proper class.
- Check if you have compiled proper class from your source.
![]()
I have just solved this error by restarting my Eclipse and run the applcation. The reason for my case may because I replace my source files without closing my project or Eclipse. Which caused different version of classes I was using.
![]()
Try this way: remove all .class files under your project directories (and, of course, all subdirectories). Rebuild.
Sometimes mvn clean (if you are using maven) does not clean .class files manually created by javac . And those old files contain old signatures, leading to NoSuchMethodError .
Just adding to existing answers. I was facing this issue with tomcat in eclipse. I had changed one class and did following steps,
Cleaned and built the project in eclpise
mvn clean install
Still I was facing same error. Then I cleaned tomcat, cleaned tomcat working directory and restarted server and my issue is gone. Hope this helps someone
![]()
These problems are caused by the use of the same object at the same two classes. Objects used does not contain new method has been added that the new object class contains.
These problems are caused by the concomitant 02 similar class (1 in src, 1 in jar file here is gateway.jar)
To answer the original question. According to java docs here:
«NoSuchMethodError» Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
- If it happens in the run time, check the class containing the method is in class path.
- Check if you have added new version of JAR and the method is compatible.
![]()
![]()
I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.
Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.
After renaming the Test to the correct name «ProjectionTest.java» the exception went away.
NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build . Try clean build first if it doesn’t works try renaming the class name or package name and clean build. it should be fixed. Good luck.
![]()
I ran into a similar problem when I was changing method signatures in my application. Cleaning and rebuilding my project resolved the «NoSuchMethodError».
Above answer explains very well ..just to add one thing If you are using using eclipse use ctrl+shift+T and enter package structure of class (e.g. : gateway.smpp.PDUEventListener ), you will find all jars/projects where it’s present. Remove unnecessary jars from classpath or add above in class path. Now it will pick up correct one.
I ran into similar issue.
Finally I identified the root cause was changing the data type of variable.
- Employee.java —> Contains the variable ( EmpId ) whose Data Type has been changed from int to String .
- ReportGeneration.java —> Retrieves the value using the getter, getEmpId() .
We are supposed to rebundle the jar by including only the modified classes. As there was no change in ReportGeneration.java I was only including the Employee.class in Jar file. I had to include the ReportGeneration.class file in the jar to solve the issue.
![]()
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)]
![]()
Most of the times java.lang.NoSuchMethodError is caught be compiler but sometimes it can occur at runtime. If this error occurs at runtime then the only reason could be the change in the class structure that made it incompatible.
I’ve encountered this error too.
My problem was that I’ve changed a method’s signature, something like
This method was invoked from a context similar to
The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.
The problem appeared due to the fact that I only compiled the class in which the method was defined — Bank, but not the class from which the method is being called from, which contains the main() method.
This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.
My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument’s base class trough inheritance.
The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it’s a hard-reference.
The original disassembled bytecode (generated with the javap tool) looks like this:
How to Solve java.lang.NoSuchMethodError in Java?
A java.lang.NoSuchMethodError as the name suggests, is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The java.lang.NoSuchMethodError can occur in case application code is partially compiled, or in case an external dependency in a project incompatibly changed the code (e.g. removed the calling method) from one version to another. It is as shown in the illustration below as follows:
Illustration:
Now let us discuss the causes behind this exception in order to figure out how to resolve the same problem. java.lang. It occurs when a particular method is not found. This method can either be an instance method or a static method. The java.lang.NoSuchMethodError occurs when an application does not find a method at runtime. In most cases, we’re able to catch this error at compile-time. Hence, it’s not a big issue. However, sometimes it could be thrown at runtime, then finding it becomes a bit difficult. According to the Oracle documentation, this error may occur at runtime if a class has been incomparably changed. Hence, we may encounter this error in the following cases. Firstly, if we do just a partial recompilation of our code. Secondly, if there is version incompatibility with the dependencies in our application, such as the external jars.
Note: NoSuchMethodError inheritance tree includes IncompatibleClassChangeError and LinkageError. These errors are associated with an incompatible class change after compilation.
Implementation:
Now we will be proposing two examples in which first we will illustrate the thrown exception and, in later example, resolve the same via clean java problems.