1

When doing some sample coding with Java I came across ClassCastException, from where I cast the object to StaticClass. Can anyone explain what has happened here?

public void test5() throws Exception {

   System.out.println(StaticClass.obj);
   Object newInstance = ClassLoader.getSystemClassLoader().loadClass("com.StaticClass").newInstance();
   System.out.println(newInstance.getClass().getDeclaredField("obj").get(newInstance));

   Object newInstance2 = new ILoader().loadClass("com//StaticClass.class").newInstance();
   System.out.println(newInstance2.getClass().getDeclaredField("obj").get(newInstance2));

   StaticClass s = (StaticClass)newInstance2;
   System.out.println(s.obj);

   System.out.println(newInstance.getClass().getClassLoader());
   System.out.println(newInstance2.getClass().getClassLoader());

}

package com;

public class StaticClass {

   public static final Object obj = new Object();
}

package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ILoader extends ClassLoader {

 public ILoader() {
  super(null);
 }

 @Override
 protected Class<?> findClass(String name) throws ClassNotFoundException {

   File file = new File(name);

   byte[] bytes = new byte[(int)file.length()];

   try {
     new FileInputStream(file).read(bytes);
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }

   return super.defineClass("com.StaticClass",bytes, 0, bytes.length);
 }
}

output which was given by last System.out when the casting part of the code not existed is as below.

sun.misc.Launcher$AppClassLoader@133056f
com.ILoader@1ac3c08
4
  • why the double slash? com//StaticClass.class, also a class loader doesn't expect .class on the end of the class name. Dec 31, 2010 at 4:26
  • @MeBigFatGuy: I think its the relative path to the class file as asela38 is reading the same in the ILoader class.
    – Favonius
    Dec 31, 2010 at 4:34
  • it's just location of the class, so the classLoader can load it, here i used a custom ClassLoader (In here two instances of the class StaticClass exist, which loaded from two separate ClassLoaders (ILoader(which is the custom one) and sun.misc.Launcher$AppClassLoader(which loads class from java.class.path)))
    – asela38
    Dec 31, 2010 at 4:35
  • The normal way around this problem is to have an interface which is available to the current class loader and use the interface. The implementing class can be in a different class loading context but you can still use it via a common interface. Dec 31, 2010 at 8:45

2 Answers 2

2

When two class loaders load a class, you actually have two copies of the class. In your scenario when you do something like this

StaticClass s = (StaticClass)newInstance2;

Then by default your default system class loader comes into picture for casting. Since the newInstance2 is loaded from another classloader therefore it will give a ClassCastException. This will not work - they are represented by two different Class objects inside the JVM and the cast will fail.

For more details refer to the following articles and forum entries:

  1. http://onjava.com/pub/a/onjava/2003/11/12/classloader.html

  2. http://java.sun.com/developer/technicalArticles/Networking/classloaders/index.html

  3. http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html

  4. http://www.coderanch.com/t/380416/java/java/Loading-same-class-two-different

  5. Different classloaders cause ClassCastException when persisting data via Spring

0

A class is defined both by its fully qualified name and the class loader that loaded it.

This is necessary because two classes are only the same if they have the same fully qualified name and were found at the same place (same class loader).

If two classes have the same name and they were loaded from different class loader there is no guarantee that they represent the same class file.

If this is were not so it would also pose a security risk as you could then spoof Java API classes. You could create your own version of java.lang.String, load it with a different class loader and gain the privileges of other classes in java.lang (be able to see package private fields for example).

There are numerous other advantages for having a class being uniquely identified by its name and class loader. Although it's looks a little weird when code throws a ClassCastException and the classes have the same name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.