简体   繁体   English

从jar加载类时截断的类文件异常

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

I am trying to read class, stored in my jar file. 我正在尝试阅读存储在我的jar文件中的课程。

When I do like this 当我这样做的时候

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

I get java.lang.ClassFormatError: Truncated class file and byteArray appears to be empty. 我收到java.lang.ClassFormatError: Truncated class filebyteArray似乎为空。

What is the problem? 问题是什么?

I remember running into that problem in the past and remembered the solution for that. 我记得过去曾经遇到过这个问题,并且想出了解决方案。 I create input stream like this. 我创建这样的输入流。

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

But there is no need to create new JarInputStream as getInputStream already returns InputStream . 但是由于getInputStream已经返回InputStream因此无需创建新的JarInputStream So I changed to this 所以我改成了这个

InputStream stream = jarFile.getInputStream(je);

And it started to work. 它开始起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM