Getting an "Incompatible magic value' Error Java

1.2k Views Asked by At
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic 
value 813187905 in class file

I understand the error, as it's quite clear. I need to somehow get java's magic value, 0xCAFEBABE (hex) written to the .java file I'm writing programmatically first. I've read all the answers to similar questions but they all point to bringing in 3rd party libraries to write the java file programmatically.

I can't help but think that there is a relatively straight forward solution to this without bringing in a 3rd party lib? How can I write a hex value to an arbitrary file?

Right now, I'm taking a string. converting it to bytes, and then writing those bytes to a FileInputStream which then dumps to a file with .java extension. Code I'm using is below. How can I instead of writing bytes, write hex values? Encodings are not my strong suite so this problem is really giving me some trouble.

Code I'm using to write my java file:

public void writeJavaFile() throws IOException 
{
    String testString = "class test { public test() {} public void printTest()
    { System.out.println(\"yoooo\");}}";
    String filename = "test.java";
    OutputStream outputStream = new FileOutputStream(filename);
    outputStream.write(testString.getBytes());
    outputStream.flush();
    outputStream.close();
}
2

There are 2 best solutions below

0
On

I was thinking about this problem all wrong and therefore probably posted a misaligned question. I was under the assumption I was needing to compile my own java file to class file which is where the magic value is actually written.

Obviously I can just have java's compiler compile my programmatically written java file. Here is the code I used to get this to work:

   `CustomClassLoader classLoader = new CustomClassLoader();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int result = compiler.run(null,null,null, "test.java");
    System.out.println("Result: " + result);
    if (result != 0) {
       System.out.println("Error compiling class!!");
       return;
    }
    // Read in newly compiled class file
    Path path = Paths.get("test.class");
    byte[] bytes = Files.readAllBytes(path);
    // Load class into JVM
    Class myClass = classLoader.loadClazz(bytes);`
3
On

It's more likely that you downloaded a corrupted .class file. You might want to figure out if you can find the correct file somewhere. If that is impossible, you can recompile the source code again if you have it.

Even if you manage to write the magic value to the file correctly, the file itself might still contain (unrunnable) gibberish.