Search code examples
javabytecode

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?


Solution

  • 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());