Unable to create a spredsheet using XSSFWorkbook [duplicate] - java

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)

Related

What is Difference between ClassNotFoundException vs NoClassDefFoundError vs Could not find or load main class XYZ?

I explored multiple sites but could not actually understand difference between them.I would like to know the exact difference between three.
A NoClassDefFoundError is thrown,if a classfile references a class, that couldn't be found at runtime, but was available at compiletime.
(Source: https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/NoClassDefFoundError.html)
A ClassNotFoundException is 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.
(Source: https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/ClassNotFoundException.html)
The error message Couldn't find or load main class XYZ, means a lot of things:
You specified the wrong class (Typo)
The class in the classfile specified is (not) in a package. (Like java c, but the class is in the package a.b, so the command should be java a.b.c)
More information/causes: https://stackoverflow.com/a/18093929/13912132
NoClassDefFoundError - is a run-time error, thrown when the Definition of the class (which is .class file) cannot be found at run-time.
Imagine you've compiled class A.java alongside other files of your project; however, later on, you've removed compiled A.class file. So, compilation went fine, but actual bytecode of the class definition is absent, as A.class has been removed.
ClassNotFoundException - is a checked exception, thrown when your application tries to load the class through its String name, but the class isn't available on class-path.
An example can be Class.forName("com.mysql.jdbc.driver"); method call in your code, when, however, you don't have com.mysql.jdbc.driver available in your project.
Couldn't find or load main class XYZ - is an error, indicating, that the class you instruct JVM to run, doesn't contain the must have entry-point public static void main(String[] args) method, and reasons for this can be different, mainly one from this list:
you don't provide a correct Fully Qualified Name of your main class;
main method is not defined with the correct signature;
you messed up the packaging / you don't run the program with super.sub.grandchild.MainClass name;
you have .class postfix after your classname, which you should remove.
Both ClassNotFoundException and NoClassDefFoundError are caused when the JVM is not able to load a particular file, but their cause differs.
Java runtime throws ClassNotFoundException while trying to load a class at runtime only and the name was provided during runtime. In the case of NoClassDefFoundError, the class was present at compile-time, but Java runtime could not find it in Java classpath during runtime.
Couldn't find or load main class error message can be caused by various reasons, it can also be caused by ClassNotFoundException or NoClassDefFoundError.
Error: Could not find or load main class ClassName.class
Caused by: java.lang.ClassNotFoundException: ClassName.class
NoClassDefFoundError
This occurs when the JVM or a ClassLoader tries to load a class (as part of a normal method call or as part of creating a new instance using the new expression) but it can not be found while it existed when the currently executing class was compiled.
ClassNotFoundException
As mentioned in the documentation, it is thrown when an application tries to load 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.
It means that it is unknown to JVM whether the class (which is to be loaded) existed when the currently executing class was compiled.

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.

java.lang.NoClassDefFoundError only in particular conditions

My problem is that when class B tries to use A.check() my execution stops due to a java.lang.NoClassDefFoundError.
So here is my class configuration. NB: the classes are in the same packages and I have already checked that the A.class file is placed where it should be.
public class A{
// vars
// declare some public method
public synchronized static boolean check(){
//do stuff, log some info and return boolean
}
}
public class B implements Runnable{
public void run() {
A.check();
}
}
And here is my stacktrace:
java.lang.NoClassDefFoundError:
org/mypackage/A
at org/mypackage.B.run()
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException:
org/mypackage.B
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
The project is really big and class A is used lots of times before this call without any problem, so i don't think that is something relative to the classpath. Note that this is part of the last call of the software that should close up everything.
Moreover, I have two maven goals: the first one execute the questioned code without any problem, instead the second rise this error every time.
So I have solved my problem and I post here the solution so maybe can be useful for someone else.
First of all the error: java.lang.NoClassDefFoundError
This error is really different from ClassNotFoundException and this is where I'have lost a lot of time.
NoClassDefFoundError in Java is raised when JVM is not able to locate a particular class at runtime which was available at compile time. For example, if we have a method call from a class accessing any member of a Class and that class is not available during runtime then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and the name was provided during runtime, not on compile time. Many Java developer mingles this two Error and gets confused. Here I quote a really useful blog that I uesd.
So in a shorter way NoClassDefFoundError comes if a class was present during compile time but not available in java classpath during runtime.
But even with those information the problem was still there until I found the mystery: one of the reason that can place the class in a state that can be compiled but not located at runtime is that if you have static initialization that fail (e.g. in my class I had as field a static variable instantiated badly).
So remember to check for you initialization phase if you have static variables in your class this could be the reason of your java.lang.NoClassDefFoundError.
By the way I don't get why this kind of error is not raising some more meaninful errors for example java.lang.ExceptionInInitializerError or something like that.
Try to debug maven execution by running: mvn -X <your_goals>
It would be useful to see your POM file.
If you are working with spring mvc and if you made bean entry in dispatche-servlet.xml for Controller class.
Example :
<bean id="MyClass" class="com.aaps.myfolder.MyClass">
<property name="methodNameResolver">
<ref bean="methodNameResolver" />
</property>
</bean>
And if MyClass.java is not compiled & if no class file is generated in classes folder of your project folder then it wil show java.lang.NoClassDefFoundError.
So check whether the MyClass.class is created or not in classes folder if you are working with spring mvc.
Does Class A have anything that is done in a static block. You can get this exception even if a class is being loaded and static blocks fails for any reason reason. try to put in logging to see if something like this is happening.

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)

A custom String class creation

I tried to create a custom class String in java.lang package in my eclipse workspace.
initially I suspected that a same class in same package can not be created but to my utter surprise I was able to create a class (String) in same package i.e. java.lang
Now I am confused
1) why is it possible and
2) what can be the reason if that is allowed.
3) what will be the use if this type of creation of java classes is allowed in Java.
You can create a new class in java.lang package. If it was forbidden how Oracle developers would be able to develop Java at all? I am sure they use the same javac as we do.
But you will not be able to load it, because java.lang.ClassLoader (that any classloader extends) does not allow it, every class being loaded goes through this check
...
if ((name != null) && name.startsWith("java.")) {
throw new SecurityException
("Prohibited package name: " + name.substring(0, name.lastIndexOf('.')));
}
...
so you will end up in something like
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:649)
at java.lang.ClassLoader.defineClass(ClassLoader.java:785)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at Test1.main(Test1.java:11)
As for classes that shadow existing classes like your java.lang.String they cannot be loaded because the System ClassLoader (default one) uses "parent first" strategy, so java.lang classes will be loaded from rt.jar with bootstrap classloader. So you will need to replace String.class in rt.jar with your version. Or override it using -Xbootclasspath/p: java option which prepends paths to bootstrap class loader search paths. So you can
1) copypaste real String.java content into your String.java
2) change a method, eg
public static String valueOf(double d) {
return "Hi";
}
and compile your String.java
3) create a test class
public class Test1 {
public static void main(String[] args) throws Exception {
System.out.println(String.valueOf(1.0d));
}
}
4) run it as
java -Xbootclasspath/p:path_to_your_classes Test1
and you will see
Hi
This is called class shadowing.
1.) It is possible because java classes are not statically linked, but linked at class load time.
2.) If it was not allowed, then the whole class loading would be a lot more difficult to achieve. Then for example you would also have to build your project against a specific Java version. because Java classes may change from version to version. This isn't going to be a maintainable approach.
3.) osgi makes use of this to be able to load different versions of the same bundle. Another common use case is to replace buggy classes in frameworks, where no other workaround is possible. However this technique should be used carefully, because errors might be hard to debug.
Please note that however shadowing classes in the java.* packages is not allowed, as this would break the Java security sandbox. So you are going to have problems at runtime.
Yes you can create the package with name java.lang and also Class named as String.
But you wont be able to run your String class.
1) why is it possible : Compiler will compile your class successfully.
2) what can be the reason if that is allowed : You have a valid name for your package and class so compiler doesn't complain.
3) what will be the use if this type of creation of java classes is allowed in Java : But there is not much use of this String class. Bootstrap class loader will load class from the sun's java.lang package. So your custom String class will not get loaded and hence it fails during run.
Bootstrap class loader is part of JVM implementation and it loads the classes of Java API (which includes java.lang.String). Also for each class which gets loaded, JVM keeps track of which class loader whether bootstrap or user-defined - loaded the class. So any attempt to load a custom String class will fail as String class is already loaded.

Categories