java.lang.NoClassDefFoundError when using class from another module - java

I added dependency of a custom jar(say some-jar.jar) in a module's pom.xml where I need to write my code inside say CustomClass.java. Now, some-jar.jar contains AnotherClass.class which I need to use in my code.
After I finish my code, build succeeds and I am able to successfully deploy the application.
But when the execution reaches my code, it throws an ERROR(not an exception) saying
java.lang.NoClassDefFoundError: com/some/package/AnotherClass
. . . and the usual stack trace.
I understand this is happening because JVM is not able to locate this file at Runtime even though at compile time it was located, but what is the solution here? What do I need to do to make it available at Runtime.
Unfortunately, due to some restrictions I cannot disclose any more information than this issue. Lets see, if it is even required.

You can either specify your dependencies in classpath like this or make a fat jar (google it)

Related

when i finish push my project,it report 'java.lang.NoSuchMethodError: org.springframework.beans.factory.support.RootBeanDefinition.setSingleton(Z)V' [duplicate]

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.

baffling logback bug TimeBasedArchiveRemover$ArhiveRemoverRunnable

Logback 1.1.7
This was during a "production" run: stack trace from Exception (actually NoClassDefFoundError is an Error):
Exception in thread "main" java.lang.NoClassDefFoundError: ch/qos/logback/core/rolling/helper/TimeBasedArchiveRemover$ArhiveRemoverRunnable
at ch.qos.logback.core.rolling.helper.TimeBasedArchiveRemover.cleanAsynchronously(TimeBasedArchiveRemover.java:231)
at ch.qos.logback.core.rolling.TimeBasedRollingPolicy.rollover(TimeBasedRollingPolicy.java:178)
at ch.qos.logback.core.rolling.RollingFileAppender.attemptRollover(RollingFileAppender.java:204)
at ch.qos.logback.core.rolling.RollingFileAppender.rollover(RollingFileAppender.java:183)
at ch.qos.logback.core.rolling.RollingFileAppender.subAppend(RollingFileAppender.java:224)
at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:100)
So I looked at the source: that class ArhiveRemoverRunnable does indeed exist in the .java file where it should have been instantiated on l. 231 (with that mis-spelling)...
Then I unpacked the executable jar (logback-core-1.1.7.jar): again, the file TimeBasedArchiveRemover$ArhiveRemoverRunnable.class exists in the package, as does file TimeBasedArchiveRemover.class.
This error is not going to happen that often: it is obviously when the "rolling" logger decides it's time to clean up the directory.
Anyone got any idea why this might happen? Troublingly I find no evidence of anyone else experiencing this...!
Potential workaround (pending):
I thought the answer to this might be to extract the source files for this .jar, edit the offending class, compile and repackage as an executable jar, and then use instead of the downloaded jar. In order to do this I started a new Gradle project in Eclipse, imported the entire source package, etc. The thing compiles (builds) OK in Eclipse-with-Gradle, with no complaints of the "NoClassDef" type...
But I'm having difficulties actually producing this executable jar. It'd be a nice thing to be able to accomplish: ability to tweak and test a downloaded dependency in some way (if really necessary).
Current not so satisfactory workaround:
In fact I have no need for a "time-based" archive remover. I'm quite happy just having archives removed on the basis of the size of all the files in the logging directory. This answer appears to solve this. However, logback is quite a beast: I'm not entirely sure: is "archive removal" the same thing as "rollover"?
If the Error occurs again, of course, I shall have to make a special utility method to log every LOGGER.xxx command within a try...catch.

NoSuchMethodError after cleaning the project

I'm currently getting this error:
java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set;
at ee.ut.cs.Parser.accessLint(Parser.java:39)
I have tried cleaning the project to no awail.
I suspect I have an error in the src/plugin/parse-htmlraw/build.xml while creating the jar file but I'm not certain. I understand that this error is because the function does not exist at runtime, but the object is created which means that the class is there, just not that function. I decompiled the .class file in created jar and it has the necessary functions.
Code is available at https://github.com/jaansusi/WCAGgrader
Q: What is wrong with the build that produces this error?
The problem is that even if I put the necessary class files in the jar I create, they are not linked correctly and the class that's called in the jar can't locate functions inside the other classes. The class object JSONObject is created but the functions inside the JSONObject class can't be found.
If you do not find the problematic version, there is a possibility you get it (especially if you are using Spring) from the following dependency -
<artifactId>android-json</artifactId>
<groupId>com.vaadin.external.google</groupId>
excluding it worked for me,
An easy way of analyzing dependencies is the maven-helper plugin in Intellij, see here
Check for the version you have used.
There might be a case where 2 different versions are being used which in turn causes this error.
To their own maven local repository com\Google\code\gson\gson, see if there are two or more version about json, will have to do is to delete the old, and remember to look at any other place in the project is introduced into the old version of the dependence, if any, change the old version of the dependence to the new version is perfectly solved this problem

Java "NoSuchMethodError"

I'm getting:
NoSuchMethodError: com.foo.SomeService.doSmth()Z
Am I understanding correctly that this 'Z' means that return type of doSmth() method is boolean? If true, then that kind of method really does not exist because this method returns some Collection. But on the other hand if I call this method, I'm not assigning its return value to any variable. I just call this method like this:
service.doSmth();
Any ideas why this error occurs? All necessary JAR files exist and all other methods from this class seems to exist.
Looks like method exists in classpath during compilation, but not during running of your application.
I don't think return type is a problem. If it was, it wouldn't compile. Compiler throws error when method call is ambiguous, and it is when two methods differ only by return type.
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.
In short - a class/jar file at runtime is not the same that you used at compile time.
This is probably a difference between your compile-time classpath and you run-time classpath.
Here is what seems to be going on:
The code is compiled with a class path that defines the doSmth() method returning a boolean. The byte-code refers to the doSmth()Z method.
At runtime, the doSmth()Z method isn't found. A method returning a Collection is found instead.
To correct this problem, check your (compile time) classpath.
The current reply just tell you why is failing. Usually is even nicer to know how to fix problems. As it is mentioned, the problem usually is that you built your program but when running or exporting it, the library is not included. So the solution is...
If you are running, check the the run configuration
Select Run tab -> Run configurations -> Select the configuration you are running -> Check the Classpath tab -> Ensure the libraries you need are there
If you are exporting (for example a war file), follow this
Select project -> Select properties -> Select Deployment Assembly -> Press Add -> Select Java Build Path Entries -> Select the libraries you want to be included in your exported file (for example a war file)
In both cases, ensure the library which you are referencing in included.
Other frequent problems for this error are not the right type of parameters or visibility but then, the compiler will detect the error before running. In this case, just check the documentation to match the function and package visibility, and ensure that the library is found in Java Build Path in your project properties.
Maybe still can help somebody, but this exception can happen also when you have on the classpath two classes in different jar files that have the same exact signature but they haven't the same public methods.
For example:
On file mylibrary1.jar you have class com.mypackage.mysubpackage.MyClass with method doSmth()
On file mylibrary2.jar you have class com.mypackage.mysubpackage.MyClass without method doSmth()
When searching the class, the classloader may find first mylibrary2.jar depending on the path precedence but can't find the method on that class.
Be sure you don't have the same package + class on two different files.
I noticed this problem occurring while testing some experimental changes in multiple linked projects, after updating them from SVN in Eclipse.
Specifically, I updated all projects from SVN, and reverted the .classpath file rather than edit it manually to keep things simple.
Then I re-added the linked projects to the path, but forgot to remove the related jars. This was how the problem occurred for me.
So apparently the run time used the jar file while the compiler used the project files.
Another way this can happen and is difficult to find:
If a signature of a method in an external jar changes in a way that there is no error found in the IDE because it's still compatible with how you call it the class might not be re-compiled.
If your build checks the files for changes and only then recompiles them, the class might not be recompiled during the build process.
So when you run it this might lead to that problem. Although you have the new jar, your own code expects still the old one but does never complain.
To make it harder it depends on the jvm if it can handle such cases. So in the worst case it runs on the test server but not on the live machine.

The activator for bundle is invalid

I'm trying to create a simple plugin in eclipse. When I run the application, I see this error in log file:
org.osgi.framework.BundleException : The activator for bundle
org.x.y.Activator for bundle org.x.y is invalid.
Do you have any idea about this error?
Check your build.properties section
If it doesn't properly specify what's supposed to be in the final binary result, it will not work. Check the .class files are where the MANIFEST.MF says they will be.
from EclipseZone, another reason for this error message:
If you see a message in the log like
The activator org.example.FooActivator for bundle org.example.foo is invalid
, then this usually means there has been a ClassNotFoundException trying to load the class in the first place, before it's even got to the start() method.
penguru adds:
The error occurs when I try create a new object from any other class in the constructor of activator class. Isn't it legal to create an object in activator plugin ?
If that class if from another plugin which has not yet been "activated", that could be your problem.
If that class is not found, that would also invalidate your plugin activator.
Basic advice: you may be better off with your initializations done in the start() method of Activator rather than its constructor.
I also faced same issue while importing plugins from different workspace. Basically, it is the bundle classpath where the framework looks for while loading the classes. When you import to a different workspace, make sure you change the class path to point to appropriate location i.e. where the class file are present.
After modifying the classpath try to clean and re-build and re-run. It should work..hopefully..
OK, I hate to be captain obvious here, but I've made this mistake before. This can also happen when you forget to extend BundleActivator.
If you have move the eclipse workspace to a new path, then you should use the project->clean before your plugin build, Or you would meet this problem.
I spent some time with this problem. Finally I noticed that the ClassNotFoundExceptions were not in line with my code, they were coming from wrong (old) packages. I checked if there was some other plugin which was messing with my debugs/exports and indeed there was, my own plugin!
So a simple fix to try if you're facing this and the CNFE's are not in line with your code:
Go to "Install new software"
Click on "already installed"
Remove all instances of your package/plugin and restart
Likely this was caused because I changed the plugin ID, making Eclipse treat it as a new plugin.
Another good site to take a look if you're getting frustrated and stuck: http://www.eclipsezone.com/eclipse/forums/t99010.html
In my case there was this Message "Activator ..invalid" but in the next exceptions there were ClassNotFound Exceptions in a Bundle were i didnt change something..
Guu(Posted a solution too) is my hero, After increasing
Bundle-ManifestVersion: 2
to
Bundle-ManifestVersion: 3
everything works :)
I got the same exception. The underlying problem was a ClassCastException. My bundle requires org.osgi.core 4.3 whereas the equinox launcher uses 4.2.
Regards
Roland
This can also happen if you name a bundle after a package in another bundle.
So:
if you have Bundle A which contains package org.my.package.name.function,
and you create bundle B with name org.my.package.name.function,
=> then the system may look for the activator there, and not find any.
I found the reason of the error. The error occurs when i try create a new object from any other class in the constructor of activator class. Isn't it legal to create an object in activator of plugin ?
In my case this exception was because of inability of Eclipse custom class loader to resolve and load all depending classes from other plugins in-time. I am not Eclipse super-guru so maybe it was my fault.
However it was fixed by disabling lazy loading of plugin. In GUI on Overview tab of MANIFEST.MF editor uncheck Activate this plug-in when one of its classes is loaded. Or directly in MANIFEST.MF delete line
Bundle-ActivationPolicy: lazy
Another captain obvious: If you change the paths of your source files (e.g. src/ to src/main/java), but forget to update build.properties, the compilation will always succeed, but your plugin will never work.
I had the same error, in my case I created my own constructor with parameters. But I didn't provide a default constructor. So after removing my constructor and initialized all within the start() method, it worked like charme.
I also met the same error. The activator XX for bundle XX is invalid, and the ClassNotFoundException.
I checked plugins\ directory, and could not find the class needed.
--
Because there is no jar file containing the needed class, there is only the corresponding directory.
For example, there is no com.hh.jar, but only com.hh directory.
So, there must be something wrong about creating the com.hh.jar.
if com.hh.jar reference other plugins, then also check them.
I solved the problem by editing MANIFEST.MF.
Open it by Plug-in Manifest Editor, in runtime tab, add needed packages in "Exported Packages".
and in the "classpath", add needed libraries, and, "." (current directory, IMPORTANT)
I have also run into this isue when 'bundle-izing' plain jar files. If some dependencies are not resolved, or jars depend on a higher JAVA version than the one you're using, the activator will not start, giving the above exception. The quick way to find out if this is the problem is to remove the jars from the bundle-classpath (runtime tab of the manifest) and check if the activator will run correctly.

Categories

Resources