Search code examples
javaclassclassloaderloader

Loading an array with a classloader


I'm trying to run this code:

public class ClassLoaderTest
{
  public static void main(String[] args) throws Exception
  {
    Object[] obj = new Object[]{};
    String cname = obj.getClass().getName();
    System.out.println(cname);

    ClassLoaderTest.class.getClassLoader().loadClass(cname);
  }
}

But it throws a ClassNotFoundException. Interestingly, if I instead use this line:

Class.forName(cname);

it works just fine.

Whats going on here?

edit: I'm using Java 6. The println prints this:

[Ljava.lang.Object;

Solution

  • They are not the same at all,

    Class.forName return the Class object associated with the class of the given name.

    In your example, you give to loadClass a String that represent the name of a class, instead of giving it directly a class.

    This method does allow you to give a name, however it must be the binary name of the class, not just the class name.

    Any class name provided as a String parameter to methods in ClassLoader must be a binary name as defined by The Java™ Language Specification.