本文介绍了自定义Java类加载器和内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法(在我自己的类加载器中),该方法从zip加载类:

I have this method (in my own classloader) that loads classes from zip:

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);
    }
}

我尝试加载的zip看起来像这样:

The zip that im trying to load looks like this:

TestClass.class
TestClass$SomeOtherInnerClass.class

我的问题是defineClass()无法加载TestClass $ SomeOtherInnerClass.如果在实际的TestClass之前加载此类,则会得到以下信息:

My problem is that defineClass() fails to load the TestClass$SomeOtherInnerClass. If this class is loaded before the actual TestClass i get this:

java.lang.NoClassDefFoundError: TestClass

我也尝试先加载TestClass.class,但随后我收到此错误:

I also tried to load the TestClass.class first but then im getting this error:

java.lang.ClassFormatError: Wrong InnerClasses attribute length in class file TestClass

我在做错什么吗?

推荐答案

我看来您可能没有覆盖 ClassLoader.findClass().否则,您要扩展的 ClassLoader 不知道如何找到这些类.

I looks like you may not be overriding ClassLoader.findClass(). Without doing that, the ClassLoader you are extending does not know how to find these classes.

使用仅在该类的私有静态Map< String,Class<?>> 中查找的内容覆盖该函数.加载每个类时,将其放入该地图.

Override that function with something that simply looks up in a private static Map<String, Class<?>> for the class. As you load each class, put it into that map.

困难在于按正确的顺序加载类,因为当前的实现方式不允许您跳回搜索Zip并从新的 findClass()方法.

The difficulty will be in loading classes in the correct order, as your current implementation will not allow you to jump back to searching the Zip and calling defineClass() from your new findClass() method.

这篇关于自定义Java类加载器和内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:51