【问题标题】:Creating a ClassLoader to load a JAR file from a byte array创建 ClassLoader 以从字节数组加载 JAR 文件
【发布时间】:2013-05-12 05:53:35
【问题描述】:

我正在寻找编写一个自定义类加载器,它将通过自定义网络加载JAR 文件。最后,我需要处理的只是 JAR 文件的字节数组。

我无法将字节数组转储到文件系统并使用URLClassLoader
我的第一个计划是从流或字节数组创建JarFile 对象,但它只支持File 对象。

我已经写了一些使用JarInputStream的东西:

public class RemoteClassLoader extends ClassLoader {

    private final byte[] jarBytes;

    public RemoteClassLoader(byte[] jarBytes) {
        this.jarBytes = jarBytes;
    }

    @Override
    public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> clazz = findLoadedClass(name);
        if (clazz == null) {
            try {
                InputStream in = getResourceAsStream(name.replace('.', '/') + ".class");
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                StreamUtils.writeTo(in, out);
                byte[] bytes = out.toByteArray();
                clazz = defineClass(name, bytes, 0, bytes.length);
                if (resolve) {
                    resolveClass(clazz);
                }
            } catch (Exception e) {
                clazz = super.loadClass(name, resolve);
            }
        }
        return clazz;
    }

    @Override
    public URL getResource(String name) {
        return null;
    }

    @Override
    public InputStream getResourceAsStream(String name) {
        try (JarInputStream jis = new JarInputStream(new ByteArrayInputStream(jarBytes))) {
            JarEntry entry;
            while ((entry = jis.getNextJarEntry()) != null) {
                if (entry.getName().equals(name)) {
                    return jis;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

这可能适用于小的JAR 文件,但我尝试加载一个几乎包含2000 类的2.7MB jar 文件,它花费了160 ms 来遍历所有条目,更不用说加载找到的类。

如果有人知道比每次加载类时迭代 JarInputStream 的条目更快的解决方案,请分享!

【问题讨论】:

  • 我在以前从事的一个项目中继承了一个类似的类加载器。那里也非常慢。除此之外,它还让我很头疼。最后学到的教训是除非你真的需要,否则不要使用自定义类加载器。
  • 我不得不问......将它存储在文件中有什么问题?我的意思是,罐子可以是任意大小的,将所有加载的罐子永远保存在内存中听起来是一个非常糟糕的主意。这也意味着您将保留 Jar 字节、缓存的条目以及加载的类……您需要支付 3 倍的罚款。
  • @wyr0 您还期望得到一个不会将 jar 的内容存储到文件系统中的答案,即使它更快且可扩展得多?

标签: java arrays jar classloader


【解决方案1】:

尽你所能

首先,您无需使用JarInputStream,因为它只是将清单的支持添加到ZipInputStream 类中,我们在这里并不真正关心。您不能将条目放入缓存中(除非您直接存储每个条目的内容,这在内存消耗方面会很糟糕),因为 ZipInputStream 并不意味着共享,因此无法同时读取。您可以做的最好的事情是将条目的名称存储到缓存中,以便仅在我们知道条目存在时迭代条目。

代码可能是这样的:

public class RemoteClassLoader extends ClassLoader {

    private final byte[] jarBytes;
    private final Set<String> names;

    public RemoteClassLoader(byte[] jarBytes) throws IOException {
        this.jarBytes = jarBytes;
        this.names = RemoteClassLoader.loadNames(jarBytes);
    }

    /**
     * This will put all the entries into a thread-safe Set
     */
    private static Set<String> loadNames(byte[] jarBytes) throws IOException {
        Set<String> set = new HashSet<>();
        try (ZipInputStream jis = 
             new ZipInputStream(new ByteArrayInputStream(jarBytes))) {
            ZipEntry entry;
            while ((entry = jis.getNextEntry()) != null) {
                set.add(entry.getName());
            }
        }
        return Collections.unmodifiableSet(set);
    }

    ...

    @Override
    public InputStream getResourceAsStream(String name) {
        // Check first if the entry name is known
        if (!names.contains(name)) {
            return null;
        }
        // I moved the JarInputStream declaration outside the
        // try-with-resources statement as it must not be closed otherwise
        // the returned InputStream won't be readable as already closed
        boolean found = false;
        ZipInputStream jis = null;
        try {
            jis = new ZipInputStream(new ByteArrayInputStream(jarBytes));
            ZipEntry entry;
            while ((entry = jis.getNextEntry()) != null) {
                if (entry.getName().equals(name)) {
                    found = true;
                    return jis;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Only close the stream if the entry could not be found
            if (jis != null && !found) {
                try {
                    jis.close();
                } catch (IOException e) {
                    // ignore me
                }
            }
        }
        return null;
    }
}

理想的解决方案

使用JarInputStream 访问 zip 条目显然不是这样做的方法,因为您需要遍历条目才能找到它,这 不是可扩展的方法,因为性能取决于关于 jar 文件中的条目总数。

为了获得最佳性能,您需要使用ZipFile 以便直接访问条目,这要归功于getEntry(name) 方法,无论您的存档大小如何。不幸的是,ZipFile 类没有提供任何构造函数来接受你的存档内容作为 byte 数组(无论如何这不是一个好习惯,因为如果文件太大,你可能会面临 OOME),但只能作为 @ 987654332@,因此您需要更改类的逻辑以便将 zip 的内容存储到临时文件中,然后将此临时文件提供给您的 ZipFile 以便能够直接访问该条目。

代码可能是这样的:

public class RemoteClassLoader extends ClassLoader {

    private final ZipFile zipFile;

    public RemoteClassLoader(byte[] jarBytes) throws IOException {
        this.zipFile = RemoteClassLoader.load(jarBytes);
    }

    private static ZipFile load(byte[] jarBytes) throws IOException {
        // Create my temporary file
        Path path = Files.createTempFile("RemoteClassLoader", "jar");
        // Delete the file on exit
        path.toFile().deleteOnExit();
        // Copy the content of my jar into the temporary file
        try (InputStream is = new ByteArrayInputStream(jarBytes)) {
            Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
        }
        return new ZipFile(path.toFile());
    }

    ...

    @Override
    public InputStream getResourceAsStream(String name) {
        // Get the entry by its name
        ZipEntry entry = zipFile.getEntry(name);
        if (entry != null) {
            // The entry could be found
            try {
                // Gives the content of the entry as InputStream
                return zipFile.getInputStream(entry);
            } catch (IOException e) {
                // Could not get the content of the entry
                // you could log the error if needed
                return null;
            }
        }
        // The entry could not be found
        return null;
    }
}

【讨论】:

  • 如果您将文件保存为临时文件,您可以使用标准的 URLClassloader,不是吗?
  • @JanCetkovsky 是正确的,但这不是 OP 想要的,我引用“我不能将字节数组转储到文件系统并使用 URLClassLoader。”
  • 我的意思是,在这种情况下,您的“理想解决方案”可以通过扩展 UrlClassLoader 来简化(因为无论如何您将文件转储到那里)。
  • @JanCetkovsky 可能是的,但这里的想法是在更多细节上显示两种方法之间的主要区别,第一种方法的时间复杂度为 O(n),另一种方法的时间复杂度为O(1)
【解决方案2】:

我将遍历该类一次并缓存条目。我还会查看 URLClassLoader 的源代码,看看它是如何工作的。如果失败,将数据写入临时文件并通过普通类加载器加载。

【讨论】:

  • 我正在考虑按照您的建议缓存条目。而且我想它不会占用比 JAR 字节数组已经使用的空间更多的空间。我查看了 URLClassLoader,但它使用的是在 Sun 包中实现的 URLClassPath 委托。我想我会采用缓存的想法。谢谢。
  • 它应该比原始文件使用更多的空间,因为它被压缩了。应该不会太多。
猜你喜欢
  • 1970-01-01
  • 2011-04-11
  • 2012-11-11
  • 2013-04-15
  • 2012-04-06
  • 2021-03-08
  • 2023-03-09
  • 1970-01-01
  • 2018-01-09
相关资源
最近更新 更多