Related
I'm trying to implement a 2-player network quiz game using RMI. I have a DispatcherInterface (interface) and Dispatcher (implementing the for the former) respecting RMI architecture.
The server model has User and Theme where a Quiz would be in a specific theme, my idea was that when a User connects into a Theme they'd be added into a Map<User,Theme> waitingList until another User comes along to play against them.
My problem lies in the implementation, while trying to implement a simple setter method for adding users to the waiting list I get the following error:
Error occurred in server thread; nested exception is:
java.lang.NoClassDefFoundError: java/sql/SQLException
Which did not make sense to me since my class path is well defined for the RMI registry and the compile/run commands.
public interface DispatcherInterface extends Remote {
public User login(ReceiverInterface client, String email, String password) throws RemoteException;
public void addToWaitingList(int userID, Theme theme) throws RemoteException;
public void addToWaitingList(User user, Theme theme) throws RemoteException;
}
The first method works perfectly with no problems while the other one doesn't regardless of its implementation (tried a simple System.out.print("test")), however I find it inconvenient as I have to loop over the list of connected users in order to get the User instance I need to add to my waitingList. So idealy I am hoping to be able to pass an instance of User to the method.
public class User implements Serializable {
public ReceiverInterface client;
public int id;
public String pseudo;
...
}
I do not understand why I can't pass the a User object to the method, especially since it's serializable.
For completeness sake, for the client part, I have implemented similarly a ReceiverInterface and Receiver that communicate with the server through a proxy (DispatcherInterface)
public class Receiver implements ReceiverInterface {
private DispatcherInterface = proxy;
private User user;
private String serverIP;
public Receiver(String serverIP) throws RemoteException, NotBoundException {
this.serverIP = serverIP;
Registry registry = LocateRegistry.getRegistry(serverIP);
this.proxy = (DispatcherInterface) registry.lookup("QuizApp");
}
...
}
Any help is appreciated.
EDIT:
I use an IDE (IntelliJ) to run my code, it uses the following command:
/usr/lib/jvm/java-10-openjdk/bin/java -javaagent:/opt/intellij-idea-ultimate-edition/lib/idea_rt.jar=41683:/opt/intellij-idea-ultimate-edition/bin -Dfile.encoding=UTF-8 -classpath /home/rand/gm4/JAVA/QuizApp/out/production/QuizApp:/home/rand/gm4/JAVA/QuizApp/lib/miglayout-swing-5.2.jar:/home/rand/gm4/JAVA/QuizApp/lib/miglayout-core-5.2.jar:/home/rand/gm4/JAVA/QuizApp/lib/sqlite-jdbc-3.23.1.jar server.Run
Which is in better terms (without the .jar dependencies), run from the project path is:
javac -d out/production/[project_name] src/server/Run.java
javac -d out/production/[project_name] src/client/Run.java
rmiregistry -J-Djava.class.path=out/production/[project_name]/
java -cp out/production/[project_name] server.Run
java -cp out/production/[project_name] client.Run
You are using jdk 10 to execute your code. In jdk 9 some of the code base was moved into modules and no longer avaliable by default, java.sql is in one of these non root module. You need to use "--add-modules java.sql" with the java command to make the java.sql package avaliable at runtime.
Since you are using intellij to run the code the following doc might help explain how to setup intellij to include this module when run from the ide. https://www.jetbrains.com/help/idea/getting-started-with-java-9-module-system.html
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)
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)
I have a bundle component,
package ipojo;
import ipojo.service.Hello;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Validate;
#Component(name="hello-factory")
#Provides
public class HelloImpl implements Hello{
#Override
public void shoutHello() {
System.out.println("HellooOOOOoooOooo!");
}
#Validate
public void start() throws Exception {
System.out.println("Hello started :)");
}
#Invalidate
public void stop() throws Exception {
System.out.println("Hello Stopped :(");
}
}
In my java application, I embedded Apache Felix, and deployed iPOJO APIs. Then, I tried to create an instance of my above component using Factory Service, as the following:
myBundle= context.installBundle("myBundlePath");
myBundle.start();
ServiceReference[] references = myBundle.getBundleContext().getServiceReferences(Factory.class.getName(), "(factory.name=hello-factory)");
if (references == null) {
System.out.println("No references!");
}
else {
System.out.println(references[0].toString());
Factory factory = myBundle.getBundleContext().getService(references[0]);
ComponentInstance instance= factory.createComponentInstance(null);
instance.start();
}
I successfully got the reference to the factory service, but at the following line:
Factory factory = myBundle.getBundleContext().getService(references[0]);
I get the following ClassCastException:
java.lang.ClassCastException: org.apache.felix.ipojo.ComponentFactory cannot be cast to org.apache.felix.ipojo.Factory`
I changed this line to:
Factory factory = (ComponentFactory) myBundle.getBundleContext().getService(references[0]);
then I got:
java.lang.ClassCastException: org.apache.felix.ipojo.ComponentFactory cannot be cast to org.apache.felix.ipojo.ComponentFactory
How can I solve my problem? Thank you.
When embedding Felix (or any other OSGi framework) you create a boundary between the classloaders. The host and the bundles are not using the same classloaders meaning that classes from inside and outside are not compatible. In other words, accessing OSGi services from the host is particularly complex and require using reflection.
For simplicity reasons, you should use the Factory service (and any other services) from a bundle and not from the host.
If you really need to use them from the host, you have to configure the OSGi framework to export all the required packages from bundle 0.
This exception means that there are classpath problems, as there are multiple versions of libraries in the classpath.
A ClassCastException when a class cannot be cast to a class of the same name is caused by an attempt to cast classes accross classloaders: it's not possible to do so, see here.
The classloader which loaded the class makes part of the class unique identifier.
So two classes with the exact same name org.apache.felix.ipojo.ComponentFactory will not be the same if they where loaded in different classloaders.
You need to debug your classpath, find the unwanted version of the library containing that class and remove it.
My co-worker and I have come across this warning message a couple times recently. For the below code:
package com.mycompany.product.data;
import com.mycompany.product.dao.GenericDAO;
public abstract class EntityBean {
public abstract GenericDAO<Object, Long> getDAO();
// ^^^^^^ <-- WARNING OCCURS HERE
}
the warning appears in the listed spot as
EntityBean.getDAO() has non-API return type GenericDAO<T, ID>
A Google search for "has non-API return type" only shows instances where this message appears in problem lists. I.e., there's no public explanation for it.
What does this mean? We can create a usage problem filter in Eclipse to make the message go away, but we don't want to do this if our usage is a legitimate problem.
Thanks!
EDIT: This warning doesn't have to do with the parameterization, as this declaration of getFactory() also results in the same warning:
public abstract class EntityBean {
protected DAOFactory getFactory() {
return DAOFactory.instance(DAOFactory.HIBERNATE);
}
}
Figured it out.
These classes (GenericDAO and DAOFactory as return types) and EntityBean were in different packages. One of the packages (the one containing EntityBean) was listed in the Export-Package: section of the manifest file, and the other package (DAOs) was not. The net effect is that the DAO classes were non-API and were being returned by an API type.
Thanks all, especially to JRL for orienting me in the right direction.
Have you looked at the following Eclipse docs: API rules of engagement and API Errors and Warnings Preferences ?