I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it?
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.
java -verbose:class <other args>
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...
clean install
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:
Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)
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.
In properties:
<jackson.version>2.8.7</jackson.version>
And as dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
2) But also it can be solved using Dependency Exclusions.
By the same principle as below in example:
<dependency>
<groupId>group-a</groupId>
<artifactId>artifact-a</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
Dependency with unwanted version will be excluded from your project.
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.)
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.
e.g.
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
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.
Related : https://reflectoring.io/nosuchmethod/
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
Short answer;
Add this maven dependency;
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<rules>
<dependencyConvergence />
</rules>
</configuration>
</plugin>
Then run this command;
mvn enforcer:enforce
Maybe this is the cause your the issue you faced.
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
Restarted tomcat
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.
ex:
filenotnull=/DayMoreConfig.conf
16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775
16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) )
Exception in thread "main" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V
at gateway.smpp.USSDClient.bind(USSDClient.java:139)
at gateway.USSDGW.initSmppConnection(USSDGW.java:274)
at gateway.USSDGW.<init>(USSDGW.java:184)
at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)
-bash-3.00$
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.
App/
src/
com.example/
Projection.java
Test/
src/
com.example/
Projection.java
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.
Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I
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.
Best Explanation: https://www.journaldev.com/14538/java-lang-nosuchmethoderror
I've encountered this error too.
My problem was that I've changed a method's signature, something like
void invest(Currency money){...}
into
void invest(Euro money){...}
This method was invoked from a context similar to
public static void main(String args[]) {
Bank myBank = new Bank();
Euro capital = new Euro();
myBank.invest(capital);
}
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:
#7 = Methodref #2.#22 // Bank.invest:(LCurrency;)V
After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.
Hope this helps.
The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.
I had a similar problem with my Gradle Project using Intelij.
I solved it by deleting the .gradle (see screenshot below) Package and rebuilding the Project.
.gradle Package
I had faced the same issue. I changed the return type of one method and ran the test code of that one class. That is when I faced this NoSuchMethodError. As a solution, I ran the maven builds on the entire repository once, before running the test code again. The issue got resolved in the next single test run.
One such instance where this error occurs:
I happened to make a silly mistake of accessing private static member variables in a non static method. Changing the method to static solved the problem.
I am currently migrating an Eclipse app to Android Studio.
This app was using the in app billing.
My main problem is to compile the project and the aidl file (I guess you all use this file)
I get this error message:
Gradle: error: cannot find symbol class IInAppBillingService
Gradle: error: package IInAppBillingService does not exist
So, following some tutorials, I move this file from com.mypackage.billing to src/main/aidl
(see this reference)
But as soon, as I do that, I get this message:
Gradle: Execution failed for task ':xxxxxxxxxxx:compileDebugAidl'.
Failed to run command:
(...) C:\Users\xxxx\AndroidStudioProjects\xxxxxxProject\xxxxxxx\src\main\aidl\IInAppBillingService.aidl:45
interface IInAppBillingService should be declared in a file called
com\xxxxxxxx\billing\IInAppBillingService.aidl.
The message is clearly a contradiction with the post from the Google bug page I linked above.
Anyone suceeded to make this aidl file to work and can help me?
Just to inform, some links I followed:
http://tools.android.com/tech-docs/new-build-system/user-guide
http://developer.android.com/guide/components/aidl.html
Adding this as an answer since it seemed to help quite a few people.
Create a new directory named 'aidl' under 'src/main/'. It should look like 'src/main/aidl'.
Add a new package name 'com.android.vending.billing' to the directory 'src/main/aidl'
Locate your sdk location and go to "sdk\extras\google\play_billing". Default location for the sdk is "C:\Program Files (x86)\Android\android-sdk". If you custom changed it, then you will have to figure out the location through the sdk manager.
Copy 'IInAppBillingService.aidl' into the package created above. In the end, it should look similar to the image below.
Rebuild project and it should be good to go.
Note: Make sure you include the necessary import if your reference isn't working
import com.android.vending.billing.IInAppBillingService;
https://issuetracker.google.com/issues/36973270
Edit From Comment
After I did this, the references to IInAppBillingService in my code were still highlighted as errors, but after rebuilding the app, the class was recognized
Just as the error message says, you need to put IInAppBillingService.aidl in the correct directory dictated by it's package (com.android.vending.billing).
Within the src/main/aidl/ folder you already have, put the .aidl file in com/android/vending/billing/.
Create new directory under src/main called aidl
Right click on directory aidl, select new->add package
Enter Name of the package com.android.vending.billing
Copy IInAppBillingService.aidl from the directory Android/Sdk/extras/google/play_billing to the directory App_name/app/src/main/aidl/com/android/vending/billing
Now go ahead with InApp billing coding and while defining InApp related services you will get an error can not resolve symbol IInAppBillingXXXXXX
Now goto to Build from android studio menu , click on Rebuild Project. This will generate IInAppBillingService.java file inside App_Name/app/build/generated/source/aidl/debug/com/android/vending/billing. This will solve the issue.
The rest of posts here didn't work for me till I created a new folder like shown here.
Add this code in build.gradle
android {
sourceSets {
main {
aidl.srcDirs = ['src']
}
}
}
Rebuild and import aidl class
The above answers concentrate on file location, but it appears you already had that set correctly. I experienced this same issue in Android Studio, but none of the listed answers resolved it, and I banged my head against it for an hour. Eventually, I realized that I was missing an obvious import:
import com.android.vending.billing.IInAppBillingService;
Once I added that it resolved this error message.
This import isn't mentioned in any of the Google Billing docs or included in any of the code examples that I found. While it may be obvious to experienced Java developers, beginners just trying to learn their first project may need it explicitly pointed out.
We need to add
create folder - src/main/aidl/packagename and place aidl file under this.
In the aidl file - mention the package name.
package packagename
Now clean the project, rebuild the project - We can the corresponding java file for the aidl generated in app\build\generated\source\aidl\debug\packagename\youraidl.java
I know it sounds so easy, but I copy paste from google sample all folder
https://github.com/googlesamples/android-play-billing/tree/master/TrivialDrive/app/src/main
aidl/com/android/vending/billing
copied into project aidl ( I had set project view in Android Studio)
and next I clean and rebuild project and it found a reference.
I've tried every solutions, but the problem was that Android Studio had compiled, with any apparent reason, in a different build type of the module that contains the AIDL packages than it was specified by the settings.
From debug to release, so the other modules couldn't see the AIDL pkg.
Switching from debug to release and turns back, solved my problem.
restarting Android Studio worked for me
a second silly thing that took me a while. I dropped the code on Android Studio to allow him create the file, but he created a .java (as expected) instead a .aidl Jiji, stupid of me
if you do all the names correct go to Build>rebuild project
it worked for me
I use Android Studio 4.1, just right click mouse -> New -> AIDL -> AIDL File.
A file will be created and placed in the [src/main/aidl] folder automatically. The aidl folder will also be created if it does not exist.
This function only supports min sdk 16+. My old project still can be supported, you can temporarily modify the min sdk to 16, create aidl and build project. After the relative interface and class be generated, recover the min sdk settings, it also works and builds project well then.
I found this bug http://code.google.com/p/android/issues/detail?id=20731 that is resolved but it did not fix this exactly, but I see in comments that this is mentioned there as problem. Is there some way in eclipse to setup dependencies in project somehow , that I will be able to normally jump to source when I am in eclipse editor ? I tried numerous ways to solve this.
My setup is:
Android project that has Android Library setup in Android>Library
Android Library project that is within workspace and have dependency on Java library project
Java Library project that is within workspace and is opened as class file instead of source !!!
Including java library project through build path normally (this is causing build to fail)
[2012-03-13 11:07:21 - Taxicar Driver Android] Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lrensoft/java/collections/GenericIterator;
[2012-03-13 11:07:21 - Taxicar Driver Android] Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2012-03-13 11:07:21 - Taxicar Driver Android] Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:163)
Not including , project runs ok , but editor is jumping to library class files.
Note that I have to include Android Library project through build path , even though it runs ok without it (it is enough to set is as dependent android library) , but when I remove it I get also those files as class files :) .
So I think that right way is not including projects through build path at all but how then setup project to jump to source ?
I had a similar problem - Open Declaration command would bring up the .class file instead of the .java file. My problem however was occurring when I would use Open Declaration in my Android app project to goto some source in my Android Library project. By following some instructions from a comment on this blog post Eclipse now takes me to the .java file (instead of the .class file) when I use the Open Declaration command.
The instructions are:
Right click on your project, select Properties
Select Java Build Path page
Select Order and Export tab
Select each library project your project depends on, and use Top or Up to move it above the projects outputs. Eg. move all library projects to the top.
That fixed the goto .java instead of .class file issue for me.
(Unfortunately though, after making these changes, this issue appears (at least it did for me): Could not find Library.apk!)
I then setup my workspace as you describe in your question (Android App depends on Android Library project depends on Java Library project) I find that Open Declaration is always taking me to .java files, so it all appears to be working ok in this respect.
Refactoring
I tried to refactor a method which is defined in a class in the Android Library. A popup with a "problem" of
Binary references to a refactored element have been found. They will
not be updated, which may lead to problems if you proceed.
However after pressing Continue the refactoring took place without any issues.
I then tried to refactor a method which is defined in a class in the Java Library. I didn't get any popups this time, and the refactoring worked.
The java library aspect might just work these days because the bugs you guys mentioned have been fixed... (I am using Eclipse 4.2.0 with ADT 20.0.3). I thought I would add this answer however incase it helps someone out with issues of Open Declaration jumping to .class instead of .java file.
I found solution. I have to create Android library from my java library as well and then include it as android library as well as Java library , Then I have to reorder build path export items so Android "Library Projectsā€¯ are last . And well not much work, Now even rename refactoring works , with some warning but works :) , Well I am happy developer again.
When I attempt to run my Android application I get the following message:
your project contains error(s), please fix them before running your application
All I did was to clean the application and everything went wrong.
Normally, you would see a red asterisk against the offending file and the corresponding line with the error. But in this case I get no such indication.
Screenshots:
Sounds like you have a syntax error in one of your XML files, or an invalid file name.
When you do a clean it deletes certain files, it would then automatically build, if you have syntax errors the R.java file won't be generated and you will have the above error.
you can check in android console(window->show view->console),it will give some more information,check it once,check your build path if your are import your project somewhere else and the project uses 3rd party libraries or you may have problems with your XML resources.
Found the source of my mysterious error.
It turns out it was a imported java class I had forgotten about which I wasn't using and caused the error to showup when I "cleaned" the project.
I visited the build path where I saw it had an associated error. I removed it and all was well.