Loading an array with a class loader

I am 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. I wonder if I use this line instead:

 Class.forName(cname); 

It works great.

What is going on here?

edit: I am using Java 6. println prints this:

 [Ljava.lang.Object; 
+5
source share
3 answers

They are not the same at all

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

In your example, you specify loadClass a String that represents the name of the class, instead of giving it the class itself.

This method allows you to specify a name, but there must be a binary name this class, not just the class name.

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

+3
source

Firstly, using the classloader to load and load the java.lang.Object array is unlikely to work (since java.lang.Object loaded by the classloader by default). Then the name indicated

 Object[] obj = new Object[]{}; String cname = obj.getClass().getName(); System.out.println(cname); 

- [Ljava.lang.Object; . Obviously, this is not a class that ClassLoader can resolve - javadoc says (in part). A class loader is an object that is responsible for loading classes; Note that he does not say that he is responsible for loading arrays. Reflex arrays process java.lang.reflect.Array , in which, in particular, the Array class provides static methods for dynamically creating and accessing Java arrays. which seems to be what you are looking for.

+1
source

Looking at the source code around a line where an exception is thrown , it looks like it is trying to create a class file name for example:

 String path = name.replace('.', '/').concat(".class"); 

Given that the value of cname is [Ljava.lang.Object; , I am not particularly surprised that the .class file was not found.

+1
source

All Articles