简体   繁体   English

加载使用ASM创建的类文件时,为什么会出现魔术值错误?

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

I wrote a byte array created with ASM to a file using the following code: 我使用以下代码将使用ASM创建的byte数组写入了文件:

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

The file is loaded using the following code: 使用以下代码加载文件:

@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;
}

The class is found by my ClassLoader , but I get a ClassFormatError the magic value is 4022320623. 该类是由我的ClassLoader找到的,但是我得到了ClassFormatError,魔术值为4022320623。

What is the cause of this behaviour? 这种行为的原因是什么?

The problem seems to be the way the file is read (using Apache's Commons IO library). 问题似乎是读取文件的方式(使用Apache的Commons IO库)。 Using the following to read the file works just fine: 使用以下内容读取文件就可以了:

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

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

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