ClassLoader and inner classes
I have this method (in my own classloader) that loads classes from zip:
Code Java:
ZipInputStream in = new ZipInputStream(new FileInputStream(zip));
ZipEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (!entry.isDirectory()) {
byte[] buffer = new byte[(int) entry.getSize()];
in.read(buffer);
if (!entry.getName().endsWith(".class"))
continue;
String name = entry.getName().replace(".class", "").replace("/", ".");
Class<?> cls = this.defineClass(name, buffer, 0, buffer.length);
this.resolveClass(cls);
}
}
The zip that im trying to load looks like this:
Quote:
TestClass.class
TestClass$SomeOtherInnerClass.class
My problem is that defineClass() fails to load the TestClass$SomeOtherInnerClass. If this class is loaded before the actual TestClass i get this:
Quote:
java.lang.NoClassDefFoundError: TestClass
I also tried to load the TestClass.class first but then im getting this error:
Quote:
java.lang.ClassFormatError: Wrong InnerClasses attribute length in class file TestClass
Please help me:-??
Re: ClassLoader and inner classes
The problem is that the class loader cannot load the inner class. For example, URLClassLoader assumes all requests are for outer classes.
Try this:
Thread.currentThread().getContextClassLoader().loa dClass( classFQN );
This works, even for inner classes. Many people recommend creating your own class loader or extending URLClassLoader but that is not actually necessary, most of the time.