Monday, May 16, 2011

ClassCastException while trying to cast to the same object

Recently I wanted to know how application servers are reloading jsp file.  So thought of finding it myself. Tried writing a ClassLoader that extends java.lang.ClassLoader which always loads class files from the disc and not from the memory.

public class PrintObj
{
         public void print()
         {
                  System.out.println(" one ");
          }
}


public class MyClassLoader extends ClassLoader
{
           public Class findClass()
           {
                      //load it from the disc and return the Class object 
            }
}


public class ClassLoaderTest
{
       public static void main(String a[])
       {
                 ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
                 //it loads it from the memory
                  PrintObj l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
                  l1.print();
                 

                 MyClassLoader loader = new MyClassLoader();   
                 PrintObj l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
                 l2.print();
                 

        }
}

When I am trying to execute the below code, it throws
Exception in thread "main" java.lang.ClassCastException: PrintObj cannot be cast to PrintObj. Bolded line shows ClassCastException. Interested to know that it collides with the existing PrintObj loaded by the system class loader. Then had to create an interface call Print and then made PrintObj implements that Print interface.

public interface Print
{
       public void print();
}


public class PrintObj implements Print
{
       System.out.println(" one ");
}


After doing the above change below code runs with out any problem.

ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
Print l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();

MyClassLoader loader = new MyClassLoader();   
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();


Now other issue when I tried to load the class second time it throws ,

MyClassLoader loader = new MyClassLoader();   
 Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
  l2.print();

 Print l3 = loader.loadClass("PrintObj").newInstance();

Exception in thread "main" java.lang.LinkageError: loader (instance of  MyClassLoader): attempted  duplicate class definition for name: "PrintObj". Then finally realized that a new ClassLoader() instance has to be created to reload a class every time from the disc. 

No comments:

Post a Comment