[英]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 file
, byteArray
似乎為空。
問題是什么?
我記得過去曾經遇到過這個問題,並且想出了解決方案。 我創建這樣的輸入流。
InputStream stream = new JarInputStream(jarFile.getInputStream(je));
但是由於getInputStream
已經返回InputStream
因此無需創建新的JarInputStream
。 所以我改成了這個
InputStream stream = jarFile.getInputStream(je);
它開始起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.