load class file from classpath - java

I want to load class files from module dependencies (external jar files in the classpath). When I tried getResourceAsStream I got null pointer exception:
ClassParser parser = new ClassParser(this.getClass().getResourceAsStream("org/apache/tools/ant/taskdefs/optional/net/FTP.class"), "FTP.class");
Exception in thread "main" java.lang.NullPointerException
at com.sun.org.apache.bcel.internal.classfile.ClassParser.<init>(ClassParser.java:101)
at ParaNamesTest.printUtilsParNames(ParaNamesTest.java:52)
at ParaNamesTest.main(ParaNamesTest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
ant.jar on myclasspath but still java can't find it what should I do?

You ask the class loader of your class (this.getClass()) for a resource from a different JAR, this won't work.
Try replacing ... (this.getClass().getResourceAsStream(... by ... (FTP.class.getResourceAsStream(... whith FTP being imported as org.apache.tools.ant.taskdefs.optional.net.FTP.
If you have the class name only at runtime, you can dynamically get a Class object by using the fully qualified class name and Class.forName:
String className = "org.apache.tools.ant.taskdefs.optional.net.FTP";
... (Class.forName(className).getResourceAsStream( ...

If you getting null for this resource it means this class could not be found in your class path. I would try #Philipp's suggestion (not because its more likely to work) but because it will make it obvious if this class is on your class path.

use Class.forName("java.lang.String") for example to get String.class

Related

NoClassDefFoundError loading class with URLClassLoader

We are trying to support plugins for our product and I am using reflection to load a class from a jar.
I create a URL ClassLoader and add all the dependency jars as URLs.
I use that ClassLaoder to load the primary class of the plugin.
I get an instance of the class and a Method reference (a run() method).
When I invoke the method I get this exception:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
This class is in log4j-api-2.10.0.jar, which is included in the classpath of the ClassLoader.
I can see the URL in the classloader in debug so I know its properly referenced.
Sometimes I get a different error, saying that it can't initialize one of my classes but that class is nothing special, no statics or anything.
The primary class that's being loaded by reflection is calling a second class that uses Log4j 2.
When the primary class run() method tries to instantiate the 2nd class that's where this problem occurs.
There is nothing static in either class other than the Logger.
In the debugger I can see from the Method ref that the class was indeed loaded with the URL ClassLoader we created.
This code has been working for a decade and the only thing we've changed is the upgrade to Log4j 2 in the plugin.
The class doing the reflective plugin load is just a normal class in the classpath of the application.
Any help would be greatly appreciated.
Ussing Drizzle's suggestion I get:
Exception in thread "ServerStatus:update_timer:" java.lang.ExceptionInInitializerErrorException in thread "ServerStatus:update_timer:" java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method) at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source) at java.lang.Class.forName(Unknown Source)
at ...
at java.lang.Thread.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassCastException: java.util.Vector cannot be cast to java.lang.StringCaused by: java.lang.ClassCastException: java.util.Vector cannot be cast to java.lang.String
at org.apache.logging.log4j.util.SystemPropertiesPropertySource.forEach(SystemPropertiesPropertySource.java:39)
at org.apache.logging.log4j.util.SystemPropertiesPropertySource.forEach(SystemPropertiesPropertySource.java:39)
at org.apache.logging.log4j.util.PropertiesUtil$Environment.reload(PropertiesUtil.java:330) at org.apache.logging.log4j.util.PropertiesUtil$Environment.reload(PropertiesUtil.java:330)
at org.apache.logging.log4j.util.PropertiesUtil$Environment.<init>(PropertiesUtil.java:322) at org.apache.logging.log4j.util.PropertiesUtil$Environment.<init>(PropertiesUtil.java:322)
at org.apache.logging.log4j.util.PropertiesUtil$Environment.<init>(PropertiesUtil.java:310) at org.apache.logging.log4j.util.PropertiesUtil$Environment.<init>(PropertiesUtil.java:310)
at org.apache.logging.log4j.util.PropertiesUtil.<init>(PropertiesUtil.java:69) at org.apache.logging.log4j.util.PropertiesUtil.<init>(PropertiesUtil.java:69)
at org.apache.logging.log4j.util.PropertiesUtil.<clinit>(PropertiesUtil.java:49) at org.apache.logging.log4j.util.PropertiesUtil.<clinit>(PropertiesUtil.java:49)
Update: Log4j 2 version 2.10.x and later have bugs. Loading classes reflectively reveals the bugs. Switching back to 2.8.2 and the above exception goes away. However, now I get ClassNotFound for one of my classes, still.
Backing Log4j down to 2.8.2 resolved issue. Its a bug on Log4j. Thanks for the help. Man that was hard to find.
this might be helpful for resolving java.lang.NoClassDefFoundError
try {
Class.forName("org.apache.logging.log4j.util.PropertiesUtil");
} catch (Exception e) {
e.printStackTrace();
}

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)

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)

java.lang.RuntimeException: java.lang.ClassNotFoundException: com.coremedia.iso.boxes.mdat.MediaDataBox

can anybody help in solving the title exception? (run in cmd of win7, Java jre7)
some examples for the detailed exception
Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: com.coremedia.iso.boxes.mdat.MediaDataBox
at com.coremedia.iso.PropertyBoxParserImpl.createBox(PropertyBoxParserImpl.java:112)
at com.coremedia.iso.AbstractBoxParser.parseBox(AbstractBoxParser.java:102)
at com.googlecode.mp4parser.BasicContainer.next(BasicContainer.java:155)
.....
Caused by: java.lang.ClassNotFoundException: com.coremedia.iso.boxes.mdat.MediaDataBox
at java.net.URLClassLoader$1.run(Unknown Source)
According to the docs,ClassNotFoundException is thrown when:
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.
The last line shows up a class loader (URLClassLoader) that tries to load a class "com.coremedia.iso.boxes.mdat.MediaDataBox" which is not accessible.
I guess there is a dependency missing; check your project setup.
According to google the class tried to be loaded belongs to a mp4Parser component.
Check if this and all needed dependencies are available on your class path.

NoClassDefFoundError: wrong name

I wrote a java program to test RESTful web services by using Netbeans7.0.1 and it works fine there. Now I wrote the build.xml file to compile the code and when I try to run the generated .class file I always got this exception:
Exception in thread "main" java.lang.NoClassDefFoundError: ClientREST (wrong name: clientrest/ClientREST)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: ClientREST. Program will exit.
The name and path are correct, so any thoughts why I'm getting this exception?
Exception in thread "main" java.lang.NoClassDefFoundError: ClientREST
So, you ran it as java ClientREST. It's expecting a ClientREST.class without any package.
(wrong name: clientrest/ClientREST)
Hey, the class is trying to tell you that it has a package clientrest;. You need to run it from the package root on. Go one folder up so that you're in the folder which in turn contains the clientrest folder representing the package and then execute java clientrest.ClientREST.
You should not go inside the clientrest package folder and execute java ClientREST.
I encountered this error using command line java:
java -cp stuff/src/mypackage Test
where Test.java resides in the package mypackage.
Instead, you need to set the classpath -cp to the base folder, in this case, src, then prepend the package to the file name.
So it will end up looking like this:
java -cp stuff/src mypackage.Test
To further note on Garry's reply: The class path is the base directory where the class itself resides. So if the class file is here -
/home/person/javastuff/classes/package1/subpackage/javaThing.class
You would need to reference the class path as follows:
/home/person/javastuff/classes
So to run from the command line, the full command would be -
java -cp /home/person/javastuff/classes package1/subpackage/javaThing
i.e. the template for the above is
java_executable -cp classpath the_class_itself_within_the_class_path
That's how I finally got mine to work without having the class path in the environment
Probably the location you are generating your classes in doesnt exists on the class path. While running use the jvm arg -verbose while running and check the log whether the class is being loaded or not.
The output will also give you clue as to where the clasess are being loaded from, make sure that your class files are present in that location.
Try the below syntax:
Suppose java File resides here: fm/src/com/gsd/FileName.java
So you can run using the below syntax:
(Make current directory to 'fm')
java src.com.gsd.FileName
Suppose you have class A
and a class B
public class A{
public static void main(String[] args){
....
.....
//creating classB object
new classB();
}
}
class B{
}
this issue can be resolved by moving class B inside of class A and using static keyword
public class A{
public static void main(String[] args){
....
.....
//creating class B
new classB();
static class B{
}
}
Here is my class structure
package org.handson.basics;
public class WithoutMain {
public static void main() {
System.out.println("With main()...");
}
}
To compile this program, I had to use absolute path. So from src/main/java I ran:
javac org/handson/basics/WithoutMain.java
Initially I tried with the below command from basics folder and it didn't work
basics % java WithoutMain
Error: Could not find or load main class WithoutMain
Caused by: java.lang.NoClassDefFoundError: org/handson/basics/WithoutMain (wrong name: WithoutMain)
Later I went back to src\main\java folder and ran the class with relevant package structure, which worked as expected.
java % java org.handson.basics.WithoutMain
With main()...
I also have encountered this error on Windows when using Class.forName() where the class name I use is correct except for case.
My guess is that Java is able to find the file at the path (because Windows paths are case-insensitive) but the parsed class's name does not match the name given to Class.forName().
Fixing the case in the class name argument fixed the error.

Categories