Java.lang.NoClassDefFoundError while using enum in a class - java

I am getting a weird java.lang.NoClassDefFoundError while deploying my code. No error when I compile it, but when I am deploying it using jetty, I get an error saying
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor#0'
defined in class path resource [applicationContext-dao.xml]:
Initialization of bean failed;
nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in class path resource [applicationContext-dao.xml]:
Invocation of init method failed;
nested exception is
java.lang.NoClassDefFoundError: com/core/model/Webhook$Event
The class looks like below
public class Webhook extends BaseObject implements Serializable {
public enum Event {
ORDER_CREATE,
ORDER_UPDATE,
ORDER_DELETE,
TICKET_CREATE,
TICKET_UPDATE,
TICKET_DELETE,
CUSTOMER_CREATE,
CUSTOMER_UPDATE,
CUSTOMER_DELETE,
MENU_ITEM_UPDATE,
CHECK_OFFER
}
private Event triggerEvent;
public Event getTriggerEvent() {
return triggerEvent;
}
public void setTriggerEvent(Event triggerEvent) {
this.triggerEvent = triggerEvent;
}
public String getTriggerEventString() {
return triggerEvent.toString();
}
public void setTriggerEventString(String triggerEvent) {
this.triggerEvent = Event.valueOf(triggerEvent);
}
}
Any Idea whats happening? It doesn't even show what like the error is in.

java.lang.NoClassDefFoundError - Usually this indicates that we previously attempted to load a class from the classpath, but it failed
for some reason - now we're trying to use the class again (and thus
need to load it, since it failed last time), but we're not even going
to try to load it, because we failed loading it earlier (and
reasonably suspect that we would fail again). The earlier failure
could be a ClassNotFoundException or an ExceptionInInitializerError
(indicating a failure in the static initialization block) or any
number of other problems. The point is, a NoClassDefFoundError is not
necessarily a classpath problem.
When I deploy in Weblogic, I often had had NoClassDefFoundError due to Weblogic cache. May try to clean cache of jetty or rename Event enum to, for example, Event1 and try again?

Related

Autowired Spring Bean is null in abstract parent class

I have a Bean that is responsible for loading the project settings from a config file, and making them available to any other object that might need them:
#Component
public class ProjectSettings extends Settings{[...]}
Now, I have a bunch of component classes that over multiple steps extend an abstract class where I want to use this bean in:
#Component
public class SomeDataDbEditor extends MongoDbEditor<SomeData> {[...]}
public abstract class MongoDbEditor<T extends MongodbEntryInterface> extends MongoDbTypedAccessor<T>{[...]}
public abstract class MongoDbTypedAccessor<T extends MongodbEntryInterface> extends MongoDbAccessor {[...]}
public abstract class MongoDbAccessor {
#Autowired
protected ProjectSettings projectSettings;
public MongoDbAccessor() throws DatabaseNotConnectedException {
String databaseName = projectSettings.getMongodbDatabaseName();
[...]
}
From my understanding, this should work since the #Autowired field is protected and thus visible from the #Component class SomeDataDbEditor. However, instead I get this exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
[...]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.company.project.module.some_data.database.accessor.SomeDataDbEditor]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:310)
... 124 more
Caused by: java.lang.NullPointerException
at io.company.project.module.database.accessor.MongoDbAccessor.<init>(MongoDbAccessor.java:26)
at io.company.project.module.database.accessor.MongoDbTypedAccessor.<init>(MongoDbTypedAccessor.java:20)
at io.company.project.module.database.accessor.MongoDbEditor.<init>(MongoDbEditor.java:19)
at io.company.project.module.some_data.database.accessor.SomeDataDbEditor.<init>(SomeDataDbEditor.java:17)
...where the referenced MongoDbAccessor.<init>(MongoDbAccessor.java:26) line is String databaseName = projectSettings.getMongodbDatabaseName();
Now, I have confirmed that the projectSettings field really is null in that case. However, I was also able to confirm that if I try to access the ProjectSettings bean in the SomeDataDbEditor, that works, and the bean gets correctly instantiated.
I know that one possible solution at this point would be to use that and just manually pass the ProjectSettings bean to the parent classes, but that would kind of defeat the point of using dependency injection in the first place. Also, I would have to adjust, like, really, really many classes for that, and I want to avoid that if at all possible.
So, does anyone have an idea why this happens here, and what I can do against it?
If you use field injection (Autowired on fields), you cannot use those fields in the constructor, since Spring can only inject the dependencies after the object was constructed, i.e. after all constructors have finished.
To circumvent that, you would either have to change to constructor injection, or alternatively do the initialization work, that you do in the constructor, in a separate method annotated with PostConstruct:
#javax.annotation.PostConstruct
public void initialize() {
}
But if you are able to change your code to constructor injection, i (as well as a lot of other people in the Spring universe) highly recommend it, since it prevents exactly such problems.

java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.text.StringEscapeUtils

I am writing a character filter function, using commons-text-1.6.jar.
The log function is okay, but then this error shows up:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.text.StringEscapeUtils
cc.openhome.web.EscapeWrapper.getParameter(EscapeWrapper.java:15)
cc.openhome.controller.Login.doPost(Login.java:30)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
cc.openhome.web.EscapeFilter.doFilter(EscapeFilter.java:16)
Code:
package cc.openhome.web;
import org.apache.commons.text.StringEscapeUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrappe
public class EscapeWrapper extends HttpServletRequestWrapper {
public EscapeWrapper(HttpServletRequest req){enter code here
super(req);
}
public String getParameter(String name){
String value = getRequest().getParameter(name);
return StringEscapeUtils.escapeHtml4(value);
}
}
Apperantly a lot of things can cause this, but I found a thread that discusses this in greter detail, you should check this out!
EDIT: The top answers from that thread:
(Accepted):
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

Unable to create a spredsheet using XSSFWorkbook [duplicate]

What is the difference between NoClassDefFoundError and ClassNotFoundException?
What causes them to be thrown? How can they be resolved?
I often encounter these throwables when modifying existing code to include new jar files.
I have hit them on both the client side and the server side for a java app distributed through webstart.
Possible reasons I have come across:
packages not included in build.xml for the client side of code
runtime classpath missing for the new jars we are using
version conflicts with previous jar
When I encounter these today I take a trail-and-error approach to get things working. I need more clarity and understanding.
The difference from the Java API Specifications is as follows.
For ClassNotFoundException:
Thrown when an application tries to
load in a class through its string
name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader.
The loadClass method in class ClassLoader.
but no definition for the class with
the specified name could be found.
For NoClassDefFoundError:
Thrown if the Java Virtual Machine or
a ClassLoader instance tries to load
in the definition of a class (as part
of a normal method call or as part of
creating a new instance using the new
expression) and no definition of the
class could be found.
The searched-for class definition
existed when the currently executing
class was compiled, but the definition
can no longer be found.
So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.
The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.
On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).
People often tend to confuse java.lang.NoClassDefFoundError with java.lang.ClassNotFoundException however there's an important distinction. For example an exception (an error really since java.lang.NoClassDefFoundError is a subclass of java.lang.Error) like
java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory
does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.
On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.
private static SomeClass foo = new SomeClass();
Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo allows you to do the same thing but its no longer free to use.
If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan ( http://www.inetfeedback.com/jarscan/ ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.
NoClassDefFoundError is a linkage error basically. It occurs when you try and instantiate an object (statically with "new") and it's not found when it was during compilation.
ClassNotFoundException is more general and is a runtime exception when you try to use a class that doesn't exist. For example, you have a parameter in a function accepts an interface and someone passes in a class that implements that interface but you don't have access to the class. It also covers case of dynamic class loading, such as using loadClass() or Class.forName().
A NoClassDefFoundError (NCDFE) happens when your code runs "new Y()" and it can't find the Y class.
It may simply be that Y is missing from your class loader like the other comments suggest, but it could be that the Y class isn't signed or has an invalid signature, or that Y is loaded by a different classloader not visible to your code, or even that Y depends on Z which couldn't be loaded for any of the above reasons.
If this happens, then the JVM will remember the result of loading X (NCDFE) and it will simply throw a new NCDFE every time you ask for Y without telling you why:
class a {
static class b {}
public static void main(String args[]) {
System.out.println("First attempt new b():");
try {new b(); } catch(Throwable t) {t.printStackTrace();}
System.out.println("\nSecond attempt new b():");
try {new b(); } catch(Throwable t) {t.printStackTrace();}
}
}
save this as a.java somewhere
The code simply tries to instantiate a new "b" class twice, other than that, it doesn't have any bugs, and it doesn't do anything.
Compile the code with javac a.java, Then run a by invoking java -cp . a -- it should just print out two lines of text, and it should run fine without errors.
Then delete the "a$b.class" file (or fill it with garbage, or copy a.class over it) to simulate the missing or corrupted class. Here's what happens:
First attempt new b():
java.lang.NoClassDefFoundError: a$b
at a.main(a.java:5)
Caused by: java.lang.ClassNotFoundException: a$b
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 1 more
Second attempt new b():
java.lang.NoClassDefFoundError: a$b
at a.main(a.java:7)
The first invocation results in a ClassNotFoundException (thrown by the class loader when it can't find the class), which must be wrapped in an unchecked NoClassDefFoundError, since the code in question (new b()) should just work.
The second attempt will of course fail too, but as you can see the wrapped exception is no more, because the ClassLoader seems to remember failed class loaders. You see only the NCDFE with absolutely no clue as to what really happened.
So if you ever see a NCDFE with no root cause, you need to see if you can track back to the very first time the class was loaded to find the cause of the error.
From http://www.javaroots.com/2013/02/classnotfoundexception-vs.html:
ClassNotFoundException : occurs when class loader could not find the required class in class path. So, basically you should check your class path and add the class in the classpath.
NoClassDefFoundError : this is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class.
Example:
public class Test1
{
}
public class Test
{
public static void main(String[] args)
{
Test1 = new Test1();
}
}
Now after compiling both the classes, if you delete Test1.class file and run Test class, it will throw
Exception in thread "main" java.lang.NoClassDefFoundError: Test
at Test1.main(Test1.java:5)
Caused by: java.lang.ClassNotFoundException: Test
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
ClassNotFoundException: thrown when an application tries to load in a class through its name, but no definition for the class with the specified name could be found.
NoClassDefFoundError: thrown if the Java Virtual Machine tries to load in the definition of a class and no definition of the class could be found.
What is the reason for getting each of them and any thought process on how to deal with such errors?
They're closely related. A ClassNotFoundException is thrown when Java went looking for a particular class by name and could not successfully load it. A NoClassDefFoundError is thrown when Java went looking for a class that was linked into some existing code, but couldn't find it for one reason or another (e.g., wrong classpath, wrong version of Java, wrong version of a library) and is thoroughly fatal as it indicates that something has gone Badly Wrong.
If you've got a C background, a CNFE is like a failure to dlopen()/dlsym() and an NCDFE is a problem with the linker; in the second case, the class files concerned should never have been actually compiled in the configuration you're trying to use them.
Example #1:
class A{
void met(){
Class.forName("com.example.Class1");
}
}
If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.
Example #2:
Class B{
void met(){
com.example.Class2 c = new com.example.Class2();
}
}
If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.
Both are run time exceptions.
Difference Between ClassNotFoundException Vs NoClassDefFoundError
ClassNotFoundException is thrown when there is attempt to load the class by referencing it via a String. For example the parameter to in Class.forName() is a String, and this raises the potential of invalid binary names being passed to the classloader.
The ClassNotFoundException is thrown when a potentially invalid binary name is encountered; for instance, if the class name has the '/' character, you are bound to get a ClassNotFoundException. It is also thrown when the directly referenced class is not available on the classpath.
On the other hand, NoClassDefFoundError is thrown
when the actual physical representation of the class - the .class file is unavailable,
or the class been loaded already in a different classloader (usually a parent classloader would have loaded the class and hence the class cannot be loaded again),
or if an incompatible class definition has been found - the name in the class file does not match the requested name,
or (most importantly) if a dependent class cannot be located and loaded. In this case, the directly referenced class might have been located and loaded, but the dependent class is not available or cannot be loaded. This is a scenario where the directly referenced class can be loaded via a Class.forName or equivalent methods. This indicates a failure in linkage.
In short, a NoClassDefFoundError is usually thrown on new() statements or method invocations that load a previously absent class (as opposed to the string-based loading of classes for ClassNotFoundException), when the classloader is unable to find or load the class definition(s).
Eventually, it is upto the ClassLoader implementation to throw an instance of ClassNotFoundException when it is unable to load a class. Most custom classloader implementations perform this since they extend the URLClassLoader. Usually classloaders do not explicitly throw a NoClassDefFoundError on any of the method implementations - this exception is usually thrown from the JVM in the HotSpot compiler, and not by the classloader itself.
With the names itself we can easily identify one from Exception and other one is from Error.
Exception: Exceptions occurs during the execution of program. A programmer can handle these exception by try catch block. We have two types of exceptions. Checked exception which throws at compile time. Runtime Exceptions which are thrown at run time, these exception usually happen because of bad programming.
Error: These are not exceptions at all, it is beyond the scope of programmer. These errors are usually thrown by JVM.
image source
Difference:
ClassNotFoundException:
Class loader fails to verify a byte code in Linking.
ClassNotFoundException is a checked exception which occurs when an application tries to load a class through its fully-qualified name and can not find its definition on the classpath.
ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass(), Class.forName() and ClassLoader.findSystemClass().
NoClassDefFoundError:
Class loader fails resolving references of a class in Linking.
NoClassDefFoundError is an Error derived from LinkageError class, which is a fatal error. It occurs when JVM can not find the definition of the class while trying to Instantiate a class by using the new keyword OR Load a class with a method call.
NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.
Similarities:
Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
Both ClassNotFoundException and NoClassDefFoundError are related to Java classpath.
Given the Class loader sussystem actions:
This is an article that helped me a lot to understand the difference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html
If an error occurs during class loading, then an instance of a
subclass of LinkageError must be thrown at a point in the program that
(directly or indirectly) uses the class or interface being loaded.
If the Java Virtual Machine ever attempts to load a class C during
verification (§5.4.1) or resolution (§5.4.3) (but not initialization
(§5.5)), and the class loader that is used to initiate loading of C
throws an instance of ClassNotFoundException, then the Java Virtual
Machine must throw an instance of NoClassDefFoundError whose cause is
the instance of ClassNotFoundException.
So a ClassNotFoundException is a root cause of NoClassDefFoundError.
And a NoClassDefFoundError is a special case of type loading error, that occurs at Linking step.
Add one possible reason in practise:
ClassNotFoundException: as cletus said, you use interface while inherited class of interface is not in the classpath. E.g, Service Provider Pattern (or Service Locator) try to locate some non-existing class
NoClassDefFoundError: given class is found while the dependency of given class is not found
In practise, Error may be thrown silently, e.g, you submit a timer task and in the timer task it throws Error, while in most cases, your program only catches Exception. Then the Timer main loop is ended without any information. A similar Error to NoClassDefFoundError is ExceptionInInitializerError, when your static initializer or the initializer for a static variable throws an exception.
ClassNotFoundException is a checked exception that occurs when we tell JVM to load a class by its string name using Class.forName() or ClassLoader.findSystemClass() or ClassLoader.loadClass() methods and mentioned class is not found in the classpath.
Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For Example, You may have seen this exception when doing the JDBC code to connect to your database i.e.MySQL but your classpath does not have JAR for it.
NoClassDefFoundError error occurs when JVM tries to load a particular class that is the part of your code execution (as part of a normal method call or as part of creating an instance using the new keyword) and that class is not present in your classpath but was present at compile time because in order to execute your program you need to compile it and if you are trying use a class which is not present compiler will raise compilation error.
Below is the brief description
You can read Everything About ClassNotFoundException Vs NoClassDefFoundError for more details.
I remind myself the following again and again when I need to refresh
ClassNotFoundException
Class Hierarchy
ClassNotFoundException extends ReflectiveOperationException extends Exception extends Throwable
While debugging
Required jar, class is missing from the classpath.
Verify all the required jars are in classpath of jvm.
NoClassDefFoundError
Class Hierarchy
NoClassDefFoundError extends LinkageError extends Error extends Throwable
While debugging
Problem with loading a class dynamically, which was compiled properly
Problem with static blocks, constructors, init() methods of dependent class and the actual error is wrapped by multiple layers [especially when you use spring, hibernate the actual exception is wrapped and you will get NoClassDefError]
When you face "ClassNotFoundException" under a static block of dependent class
Problem with versions of class.
This happens when you have two versions v1, v2 of same class under different jar/packages, which was compiled successfully using v1 and v2 is loaded at the runtime which doesn't has the relevant methods/vars& you will see this exception. [I once resolved this issue by removing the duplicate of log4j related class under multiple jars that appeared in the classpath]
ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime.However, they occur at different scenarios.
ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath.
public class MainClass
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at pack1.MainClass.main(MainClass.java:17)
NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.
class A
{
// some code
}
public class B
{
public static void main(String[] args)
{
A a = new A();
}
}
When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:
Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Spring NoClassDefFoundError: wrong name

I have the following class:
package com.spring.domain;
#Document(collection = "sportactions") // for my mongodb collection
#JsonInclude(JsonInclude.Include.NON_NULL)
public class SportAction extends Action {
//code logic
}
When I compile it, it gives me the following error:
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Handler processing failed; nested exception is
java.lang.NoClassDefFoundError: com/spring/domain/Sportaction (wrong
name: com/spring/domain/SportAction)] with root cause
java.lang.NoClassDefFoundError: com/spring/domain/Sportaction (wrong
name: com/spring/domain/SportAction)
I was confused as I can see my class is called SportAction with a capital A and not a small letter a so then I attempted to refactor my class name to see if it will work with a small letter a.
I got the following error:
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Handler processing failed; nested exception is
java.lang.NoClassDefFoundError: com/spring/domain/SportAction (wrong
name: com/spring/domain/Sportaction)] with root cause
java.lang.NoClassDefFoundError: com/spring/domain/SportAction (wrong
name: com/spring/domain/Sportaction)
The spring application will compile perfectly but this will appear at run time when I try to use the class.
I also did several clean and then build on gradle and it still doesn't work.
Does anyone know what is wrong with the code?
The error arose in this line of my java code when I try to fetch a list of Sportaction from mongodb:
List<Sportaction> sportactions = mongoTemplate.find(query, Sportaction.class);
I don't know why this error occurred, but my build.gradle file required me to build a jar like so:
task stage(type: Copy, dependsOn: [clean, build]) {
from jar.archivePath
into project.rootDir
rename {
'app.jar'
}
}
stage.mustRunAfter(clean)
clean << {
project.file('app.jar').delete()
}
When I ran it and pushed it onto my repo, I got a very strange error where my filename was now SportAction but my class name inside my java file was:
public class Sportaction
This caused a mismatch, and I tried refactoring the name to match the filename SportAction but the same wrong name error arose. I then decided to refactor the name to something else like SportEvents and then rerun the code and then it worked.
This isn't the best solution but it will have to do for now. I suspect it has something to do with the way the jar was built but I'm not sure as the app.jar was never run. The Application.main() was the class that ran when I ran my Spring app.
I'm also confused as to why my SportAction class on bitbucket does not seem to have a commit at all - see those 3 dots next to my Action file - it doesn't have a date and neither does it have a description.

NoClassDefFoundError with URLClassLoader [duplicate]

What is the difference between NoClassDefFoundError and ClassNotFoundException?
What causes them to be thrown? How can they be resolved?
I often encounter these throwables when modifying existing code to include new jar files.
I have hit them on both the client side and the server side for a java app distributed through webstart.
Possible reasons I have come across:
packages not included in build.xml for the client side of code
runtime classpath missing for the new jars we are using
version conflicts with previous jar
When I encounter these today I take a trail-and-error approach to get things working. I need more clarity and understanding.
The difference from the Java API Specifications is as follows.
For ClassNotFoundException:
Thrown when an application tries to
load in a class through its string
name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader.
The loadClass method in class ClassLoader.
but no definition for the class with
the specified name could be found.
For NoClassDefFoundError:
Thrown if the Java Virtual Machine or
a ClassLoader instance tries to load
in the definition of a class (as part
of a normal method call or as part of
creating a new instance using the new
expression) and no definition of the
class could be found.
The searched-for class definition
existed when the currently executing
class was compiled, but the definition
can no longer be found.
So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.
The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.
On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).
People often tend to confuse java.lang.NoClassDefFoundError with java.lang.ClassNotFoundException however there's an important distinction. For example an exception (an error really since java.lang.NoClassDefFoundError is a subclass of java.lang.Error) like
java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory
does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.
On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.
private static SomeClass foo = new SomeClass();
Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo allows you to do the same thing but its no longer free to use.
If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan ( http://www.inetfeedback.com/jarscan/ ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.
NoClassDefFoundError is a linkage error basically. It occurs when you try and instantiate an object (statically with "new") and it's not found when it was during compilation.
ClassNotFoundException is more general and is a runtime exception when you try to use a class that doesn't exist. For example, you have a parameter in a function accepts an interface and someone passes in a class that implements that interface but you don't have access to the class. It also covers case of dynamic class loading, such as using loadClass() or Class.forName().
A NoClassDefFoundError (NCDFE) happens when your code runs "new Y()" and it can't find the Y class.
It may simply be that Y is missing from your class loader like the other comments suggest, but it could be that the Y class isn't signed or has an invalid signature, or that Y is loaded by a different classloader not visible to your code, or even that Y depends on Z which couldn't be loaded for any of the above reasons.
If this happens, then the JVM will remember the result of loading X (NCDFE) and it will simply throw a new NCDFE every time you ask for Y without telling you why:
class a {
static class b {}
public static void main(String args[]) {
System.out.println("First attempt new b():");
try {new b(); } catch(Throwable t) {t.printStackTrace();}
System.out.println("\nSecond attempt new b():");
try {new b(); } catch(Throwable t) {t.printStackTrace();}
}
}
save this as a.java somewhere
The code simply tries to instantiate a new "b" class twice, other than that, it doesn't have any bugs, and it doesn't do anything.
Compile the code with javac a.java, Then run a by invoking java -cp . a -- it should just print out two lines of text, and it should run fine without errors.
Then delete the "a$b.class" file (or fill it with garbage, or copy a.class over it) to simulate the missing or corrupted class. Here's what happens:
First attempt new b():
java.lang.NoClassDefFoundError: a$b
at a.main(a.java:5)
Caused by: java.lang.ClassNotFoundException: a$b
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 1 more
Second attempt new b():
java.lang.NoClassDefFoundError: a$b
at a.main(a.java:7)
The first invocation results in a ClassNotFoundException (thrown by the class loader when it can't find the class), which must be wrapped in an unchecked NoClassDefFoundError, since the code in question (new b()) should just work.
The second attempt will of course fail too, but as you can see the wrapped exception is no more, because the ClassLoader seems to remember failed class loaders. You see only the NCDFE with absolutely no clue as to what really happened.
So if you ever see a NCDFE with no root cause, you need to see if you can track back to the very first time the class was loaded to find the cause of the error.
From http://www.javaroots.com/2013/02/classnotfoundexception-vs.html:
ClassNotFoundException : occurs when class loader could not find the required class in class path. So, basically you should check your class path and add the class in the classpath.
NoClassDefFoundError : this is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class.
Example:
public class Test1
{
}
public class Test
{
public static void main(String[] args)
{
Test1 = new Test1();
}
}
Now after compiling both the classes, if you delete Test1.class file and run Test class, it will throw
Exception in thread "main" java.lang.NoClassDefFoundError: Test
at Test1.main(Test1.java:5)
Caused by: java.lang.ClassNotFoundException: Test
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
ClassNotFoundException: thrown when an application tries to load in a class through its name, but no definition for the class with the specified name could be found.
NoClassDefFoundError: thrown if the Java Virtual Machine tries to load in the definition of a class and no definition of the class could be found.
What is the reason for getting each of them and any thought process on how to deal with such errors?
They're closely related. A ClassNotFoundException is thrown when Java went looking for a particular class by name and could not successfully load it. A NoClassDefFoundError is thrown when Java went looking for a class that was linked into some existing code, but couldn't find it for one reason or another (e.g., wrong classpath, wrong version of Java, wrong version of a library) and is thoroughly fatal as it indicates that something has gone Badly Wrong.
If you've got a C background, a CNFE is like a failure to dlopen()/dlsym() and an NCDFE is a problem with the linker; in the second case, the class files concerned should never have been actually compiled in the configuration you're trying to use them.
Example #1:
class A{
void met(){
Class.forName("com.example.Class1");
}
}
If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.
Example #2:
Class B{
void met(){
com.example.Class2 c = new com.example.Class2();
}
}
If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.
Both are run time exceptions.
Difference Between ClassNotFoundException Vs NoClassDefFoundError
ClassNotFoundException is thrown when there is attempt to load the class by referencing it via a String. For example the parameter to in Class.forName() is a String, and this raises the potential of invalid binary names being passed to the classloader.
The ClassNotFoundException is thrown when a potentially invalid binary name is encountered; for instance, if the class name has the '/' character, you are bound to get a ClassNotFoundException. It is also thrown when the directly referenced class is not available on the classpath.
On the other hand, NoClassDefFoundError is thrown
when the actual physical representation of the class - the .class file is unavailable,
or the class been loaded already in a different classloader (usually a parent classloader would have loaded the class and hence the class cannot be loaded again),
or if an incompatible class definition has been found - the name in the class file does not match the requested name,
or (most importantly) if a dependent class cannot be located and loaded. In this case, the directly referenced class might have been located and loaded, but the dependent class is not available or cannot be loaded. This is a scenario where the directly referenced class can be loaded via a Class.forName or equivalent methods. This indicates a failure in linkage.
In short, a NoClassDefFoundError is usually thrown on new() statements or method invocations that load a previously absent class (as opposed to the string-based loading of classes for ClassNotFoundException), when the classloader is unable to find or load the class definition(s).
Eventually, it is upto the ClassLoader implementation to throw an instance of ClassNotFoundException when it is unable to load a class. Most custom classloader implementations perform this since they extend the URLClassLoader. Usually classloaders do not explicitly throw a NoClassDefFoundError on any of the method implementations - this exception is usually thrown from the JVM in the HotSpot compiler, and not by the classloader itself.
With the names itself we can easily identify one from Exception and other one is from Error.
Exception: Exceptions occurs during the execution of program. A programmer can handle these exception by try catch block. We have two types of exceptions. Checked exception which throws at compile time. Runtime Exceptions which are thrown at run time, these exception usually happen because of bad programming.
Error: These are not exceptions at all, it is beyond the scope of programmer. These errors are usually thrown by JVM.
image source
Difference:
ClassNotFoundException:
Class loader fails to verify a byte code in Linking.
ClassNotFoundException is a checked exception which occurs when an application tries to load a class through its fully-qualified name and can not find its definition on the classpath.
ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass(), Class.forName() and ClassLoader.findSystemClass().
NoClassDefFoundError:
Class loader fails resolving references of a class in Linking.
NoClassDefFoundError is an Error derived from LinkageError class, which is a fatal error. It occurs when JVM can not find the definition of the class while trying to Instantiate a class by using the new keyword OR Load a class with a method call.
NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.
Similarities:
Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
Both ClassNotFoundException and NoClassDefFoundError are related to Java classpath.
Given the Class loader sussystem actions:
This is an article that helped me a lot to understand the difference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html
If an error occurs during class loading, then an instance of a
subclass of LinkageError must be thrown at a point in the program that
(directly or indirectly) uses the class or interface being loaded.
If the Java Virtual Machine ever attempts to load a class C during
verification (§5.4.1) or resolution (§5.4.3) (but not initialization
(§5.5)), and the class loader that is used to initiate loading of C
throws an instance of ClassNotFoundException, then the Java Virtual
Machine must throw an instance of NoClassDefFoundError whose cause is
the instance of ClassNotFoundException.
So a ClassNotFoundException is a root cause of NoClassDefFoundError.
And a NoClassDefFoundError is a special case of type loading error, that occurs at Linking step.
Add one possible reason in practise:
ClassNotFoundException: as cletus said, you use interface while inherited class of interface is not in the classpath. E.g, Service Provider Pattern (or Service Locator) try to locate some non-existing class
NoClassDefFoundError: given class is found while the dependency of given class is not found
In practise, Error may be thrown silently, e.g, you submit a timer task and in the timer task it throws Error, while in most cases, your program only catches Exception. Then the Timer main loop is ended without any information. A similar Error to NoClassDefFoundError is ExceptionInInitializerError, when your static initializer or the initializer for a static variable throws an exception.
ClassNotFoundException is a checked exception that occurs when we tell JVM to load a class by its string name using Class.forName() or ClassLoader.findSystemClass() or ClassLoader.loadClass() methods and mentioned class is not found in the classpath.
Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For Example, You may have seen this exception when doing the JDBC code to connect to your database i.e.MySQL but your classpath does not have JAR for it.
NoClassDefFoundError error occurs when JVM tries to load a particular class that is the part of your code execution (as part of a normal method call or as part of creating an instance using the new keyword) and that class is not present in your classpath but was present at compile time because in order to execute your program you need to compile it and if you are trying use a class which is not present compiler will raise compilation error.
Below is the brief description
You can read Everything About ClassNotFoundException Vs NoClassDefFoundError for more details.
I remind myself the following again and again when I need to refresh
ClassNotFoundException
Class Hierarchy
ClassNotFoundException extends ReflectiveOperationException extends Exception extends Throwable
While debugging
Required jar, class is missing from the classpath.
Verify all the required jars are in classpath of jvm.
NoClassDefFoundError
Class Hierarchy
NoClassDefFoundError extends LinkageError extends Error extends Throwable
While debugging
Problem with loading a class dynamically, which was compiled properly
Problem with static blocks, constructors, init() methods of dependent class and the actual error is wrapped by multiple layers [especially when you use spring, hibernate the actual exception is wrapped and you will get NoClassDefError]
When you face "ClassNotFoundException" under a static block of dependent class
Problem with versions of class.
This happens when you have two versions v1, v2 of same class under different jar/packages, which was compiled successfully using v1 and v2 is loaded at the runtime which doesn't has the relevant methods/vars& you will see this exception. [I once resolved this issue by removing the duplicate of log4j related class under multiple jars that appeared in the classpath]
ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime.However, they occur at different scenarios.
ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath.
public class MainClass
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at pack1.MainClass.main(MainClass.java:17)
NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.
class A
{
// some code
}
public class B
{
public static void main(String[] args)
{
A a = new A();
}
}
When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:
Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Categories