簡體   English   中英

加載使用ASM創建的類文件時,為什么會出現魔術值錯誤?

[英]Why do I get a magic value error when loading a class file created with ASM?

我使用以下代碼將使用ASM創建的byte數組寫入了文件:

try(FileOutputStream stream = new FileOutputStream(classname + ".class")) {
        stream.write(res);
    }
    catch (IOException e) {
        e.printStackTrace();
    }

使用以下代碼加載文件:

@Override
public Class<?> findClass(String name) {
    for(URL url : getURLs()) {
        File file = new File(url.getPath().substring(1) + name + ".class");
        if(file.exists()) {
            try {
                System.out.println("found class");
                byte[] bytes = IOUtils.toByteArray(new FileReader(file));
                return super.defineClass(name, bytes, 0, bytes.length);             
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

該類是由我的ClassLoader找到的,但是我得到了ClassFormatError,魔術值為4022320623。

這種行為的原因是什么?

問題似乎是讀取文件的方式(使用Apache的Commons IO庫)。 使用以下內容讀取文件就可以了:

byte[] bytes = Files.readAllBytes(file.toPath());

暫無
暫無

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

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