简体   繁体   中英

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:

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.

What is the cause of this behaviour?

The problem seems to be the way the file is read (using Apache's Commons IO library). Using the following to read the file works just fine:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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