Translate

Search This Blog

Friday 24 June 2011

Class Loaders - simplified - part 2

In my last post I said I will be discussing about NoClassDefFoundError and the ClassNotFoundException

You can load the classes in two ways one is static loading and second way is to dynamically loading the class.
  1. Static loading - load a class statically using the new operator.
  2. Dynamic loading - programmatically loading the class using the class loader functions at run time.Using Ex Class.forName/ClassLoader.findSystemClass/ClassLoader.loadClass
You can get NoClassDefFoundError for the following reason
1) You have not set the class path, so the class loader cannot find the .class file ( TestClass)
2) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class (the call to the new operator fails)
3) It could also happen if the class fails to load as the static initializer block fails for some reason.

You can get ClassNotFoundException if
1) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class , so the dynamic loading call class.forName fails.


Use the below example of a class that tries to refer to another TestClass

public class ClassLoaderExceptionTest
{
public static void main(String args[]) throws Exception
{
//Try1
Class class = Class.forName("TestClass"); //dynamically loading the class
//Throws ClassNotFoundException if TestClass is missing or removed after compilation/ not present in //class path
//Try2
TestClass testClass = new TestClass(); // static loading
//Throws NoClassDefFoundError if TestClass is missing or removed after compilation/ not present in class //path
}
}
class TestClass{
}

No comments:

Post a Comment

Please use proper blogging etiquette while posting comments.

Note: only a member of this blog may post a comment.