簡體   English   中英

從jar加載類時截斷的類文件異常

[英]truncated class file exception when load class from jar

我正在嘗試閱讀存儲在我的jar文件中的課程。

當我這樣做的時候

private void registerClasses(Path jar, List<String> classNames) throws IOException {
    JarFile jarFile = new JarFile(jar.toFile());
    Enumeration<JarEntry> e = jarFile.entries();
    while (e.hasMoreElements()) {
        JarEntry je = e.nextElement();
        if (je.isDirectory() || !je.getName().endsWith(".class")) {
            continue;
        }

        String className = je.getName().substring(0, je.getName().length() - 6).replace('/', '.');
        if (classNames.contains(className)) {
            LOGGER.info("Found class in jar [{}].", className);
            InputStream stream = new JarInputStream(jarFile.getInputStream(je));
            byte[] classBytes = IOUtils.toByteArray(stream); // empty array
            Class<?> clz = this.defineClass(className, classBytes, 0, classBytes.length);
            LOGGER.info("Defined class: [{}].", clz.getClass());
        }
    }
}

我收到java.lang.ClassFormatError: Truncated class filebyteArray似乎為空。

問題是什么?

我記得過去曾經遇到過這個問題,並且想出了解決方案。 我創建這樣的輸入流。

InputStream stream = new JarInputStream(jarFile.getInputStream(je));

但是由於getInputStream已經返回InputStream因此無需創建新的JarInputStream 所以我改成了這個

InputStream stream = jarFile.getInputStream(je);

它開始起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM