Creat inner static class instance by its name

Kérdezösködő Indián :

I need to create instances from each statically defined inner classes, but I get java.lang.ClassNotFoundException.

First, I collect the declared inner classes:

public String[] getInnerClassNames(Class<?> p_class) {
    Class<?>[] declaredClasses = p_class.getDeclaredClasses();
    String[] innerClassNames = new String[declaredClasses.length];
    for (int i = 0; i < declaredClasses.length; i++) {
        innerClassNames[i] = declaredClasses[i].getCanonicalName();
    }
    return innerClassNames;
}

where the p_class is the outer class.

Second, I do the class loading and instantiation for the given inner class name:

public Object createObjectByClassName(String p_className)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    Class<?> clazz = Class.forName(p_className);
    return clazz.newInstance();
}

This inner class name has the form: PACKAGE.OUTER_CLASS_NAME.INNER_CLASS_NAME.

What I am missing here?

Tom Hawtin - tackline :

You are missing Class.getName.

Class.getCanonicalName will return the name according to the Java Language Specification. You want the name that the JVM/bytecode is using.

The names differ because the JVM roughly matches the Java 1.0 language. The approach made to compatibility makes everything new look like a bit of a hack at the bytecode level.

Also, the constructor may well be different, as the inner class requires a reference to its context.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19115&siteId=1