java lang nosuchmethoderror что значит
Как исправить ошибку 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, мы получили бы ошибку, как показано ниже.
Есть две основные причины:
Отладка java.lang.NoSuchMethodError
Вы можете использовать java runtime option-verbose:class, чтобы получить информацию о jar, который используется для загрузки класса. Эту конфигурацию можно задать в tomcat catalina.sh или setenv.sh.
Средняя оценка / 5. Количество голосов:
Или поделись статьей
Видим, что вы не нашли ответ на свой вопрос.
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.
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.
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]
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.
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.
I had the same error:
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.
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.)
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.
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
It means the respective method is not present in the class:
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.
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
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.
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.
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.
I ran into a similar problem when I was changing method signatures in my application. Cleaning and rebuilding my project resolved the «NoSuchMethodError».
I ran into similar issue.
Finally I identified the root cause was changing the data type of variable.
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.
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.
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:
Как исправить ошибку NoSuchMethodError?
Я получаю сообщение NoSuchMethodError об ошибке при запуске моей Java-программы. Что не так и как мне это исправить?
Без дополнительной информации трудно точно определить проблему, но основная причина заключается в том, что вы, скорее всего, скомпилировали класс для другой версии класса, в которой отсутствует метод, а не той, которую вы используете при его запуске.
У меня была твоя проблема, и вот как я ее исправил. Следующие шаги являются рабочим способом добавления библиотеки. Первые два шага я сделал правильно, но последний шаг я не сделал, перетащив файл «.jar» прямо из файловой системы в папку «lib» в моем проекте eclipse. Кроме того, мне пришлось удалить предыдущую версию библиотеки как из пути сборки, так и из папки «lib».
Если у вас есть доступ для изменения параметров JVM, добавление подробного вывода должно позволить вам увидеть, какие классы загружаются из каких JAR-файлов.
Когда ваша программа запущена, JVM должна вывести на стандартную информацию, такую как:
[Загружено junit.framework.Assert из файла: / C: /Program%20Files/junit3.8.2/junit.jar]
Иногда это также может быть вызвано при компиляции с одной версией библиотеки, но с другой версией.
Это особенно вероятно, если вы написали объект и знаете, что у него есть метод. Работал на меня.
Если это причина, то трассировка стека должна показывать точку, в которой вызывается метод отражения, и вам просто нужно обновить параметры, чтобы они соответствовали фактической сигнатуре метода.
По моему опыту, это иногда встречается при модульном тестировании частных методов / полей и использовании TestUtilities класса для извлечения полей для проверки теста. (Как правило, с устаревшим кодом, который не был разработан с учетом модульного тестирования.)
Если вы пишете веб-приложение, убедитесь, что у вас нет конфликтующих версий jar-файла в каталоге глобальной библиотеки вашего контейнера, а также в вашем приложении. Вы можете не обязательно знать, какой jar-файл используется загрузчиком классов.
Эти проблемы вызваны использованием одного и того же объекта в тех же двух классах. Используемые объекты не содержат новый метод, который был добавлен в новый класс объектов.
Это означает, что соответствующий метод отсутствует в классе:
Для меня это произошло потому, что я изменил тип аргумента в функции с Object a на String a. Я мог бы решить это с чистой и построить снова
Я только что решил эту ошибку, перезапустив Eclipse и запустив приложение. Причиной моего дела может быть то, что я заменяю свои исходные файлы, не закрывая проект или Eclipse Что вызвало разные версии классов, которые я использовал.
Просто добавляю к существующим ответам. Я столкнулся с этой проблемой с котом в затмении. Я изменил один класс и сделал следующие шаги,
Очистили и построили проект в eclpise
Тем не менее я столкнулся с той же ошибкой. Затем я очистил tomcat, очистил рабочий каталог tomcat и перезапустил сервер, и моя проблема исчезла. Надеюсь, это поможет кому-то
Чтобы ответить на оригинальный вопрос. Согласно документам Java здесь :
«NoSuchMethodError» Брошенный, если приложение пытается вызвать указанный метод класса (статический или экземпляр), и у этого класса больше нет определения этого метода.
Обычно эта ошибка отлавливается компилятором; эта ошибка может возникнуть только во время выполнения, если определение класса несовместимо изменилось.
Я исправил эту проблему в Eclipse, переименовав тестовый файл Junit.
В моем рабочем пространстве Eclipse у меня есть проект App и тестовый проект.
Тестовый проект имеет проект App как необходимый проект на пути сборки.
Начал получать NoSuchMethodError.
Затем я понял, что класс в проекте Test имеет то же имя, что и класс в проекте App.
После переименования теста на правильное имя «ProjectionTest.java» исключение исчезло.
У меня была такая же ошибка:
По тому же принципу, что и в примере ниже:
Зависимость от нежелательной версии будет исключена из вашего проекта.
Я столкнулся с подобной проблемой, когда менял сигнатуры методов в своем приложении. Очистка и перестройка моего проекта решили «NoSuchMethodError».
Я столкнулся с подобной проблемой.
Наконец, я определил основную причину изменения типа данных переменной.
Мы должны восстановить банку, включив только модифицированные классы. Поскольку изменений ReportGeneration.java не было, я включил только Employee.class файл Jar. Мне пришлось включить ReportGeneration.class файл в банку, чтобы решить проблему.
У меня была такая же проблема. Это также вызвано тем, что в классах есть неоднозначность. Моя программа пыталась вызвать метод, который присутствовал в двух файлах JAR, находящихся в одном и том же месте / пути к классам. Удалите один файл JAR или выполните свой код так, чтобы использовался только один файл JAR. Убедитесь, что вы не используете один и тот же JAR или разные версии одного и того же JAR, которые содержат один и тот же класс.
DISP_E_EXCEPTION [шаг] [] [Z-JAVA-105 Java-исключение java.lang.NoSuchMethodError (com.example.yourmethod)]
В большинстве случаев java.lang.NoSuchMethodError перехватывается компилятором, но иногда это может происходить во время выполнения. Если эта ошибка возникает во время выполнения, единственной причиной может быть изменение в структуре класса, которое сделало ее несовместимой.
Я тоже столкнулся с этой ошибкой.
Моя проблема заключалась в том, что я изменил подпись метода, что-то вроде
Этот метод был вызван из контекста, аналогичного
С этой проблемой вы можете столкнуться не слишком часто, так как чаще всего проект перестраивается вручную или действие «Построение» запускается автоматически, а не просто компилирует один измененный класс.
Исходный дизассемблированный байт-код (сгенерированный с помощью инструмента javap) выглядит следующим образом:
No Such Method Error Class
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Thrown when the VM notices that a program tries to reference, on a class or object, a method that does not exist.
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
Constructs a new NoSuchMethodError that includes the current stack trace.
A constructor used when creating managed representations of JNI objects; called by the runtime.
Constructs a new NoSuchMethodError with the current stack trace and the specified detail message.
Fields
Properties
(Inherited from Throwable)
The handle to the underlying Android instance.
(Inherited from Throwable)
Returns the detail message which was provided when this Throwable was created.
Returns the detail message which was provided when this Throwable was created.
(Inherited from Throwable)
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Methods
Adds throwable to the list of throwables suppressed by this.
(Inherited from Throwable)
Returns the throwables suppressed by this.
Writes a printable representation of this Throwable ‘s stack trace to the System.err stream.
Writes a printable representation of this Throwable ‘s stack trace to the given print stream.
Writes a printable representation of this Throwable ‘s stack trace to the specified print writer.
Sets the Handle property.
Sets the array of stack trace elements.
(Inherited from Throwable)
Explicit Interface Implementations
IJavaObjectEx.IsProxy | (Inherited from Throwable) |
IJavaObjectEx.KeyHandle | (Inherited from Throwable) |
IJavaObjectEx.NeedsActivation | (Inherited from Throwable) |
IJavaObjectEx.ToLocalJniHandle() | (Inherited from Throwable) |
IJavaPeerable.Disposed() | (Inherited from Throwable) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Throwable) |
IJavaPeerable.Finalized() | (Inherited from Throwable) |
IJavaPeerable.JniManagedPeerState | (Inherited from Throwable) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Throwable) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Throwable) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Throwable) |
Extension Methods
Performs an Android runtime-checked type conversion.
How to Fix java.lang.NoSuchMethodError in Java
Table of Contents
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
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
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.
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.