2017-02-22 53 views
0

我想讀取存儲在我的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

回答

0

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

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

但有沒有必要建立新的JarInputStreamgetInputStream已經返回InputStream。所以我改成這個

InputStream stream = jarFile.getInputStream(je); 

它開始工作。