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

问题描述:

我想读取存储在我的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显示为空。

什么问题?

+0

你确定.class文件不是空的吗? – EJP

+0

是的。我提供了由IDE构建的工件 – lapots

我记得过去遇到过这个问题,想起了解决方案。我创建这样的输入流。

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

但有没有必要建立新的JarInputStreamgetInputStream已经返回InputStream。所以我改成这个

InputStream stream = jarFile.getInputStream(je); 

它开始工作。