๐งช Unit Test 001: CAFEBABE โ
๐ Preface โ
Every .class file in Java begins with the same hexadecimal value: CAFEBABE. This is known as the magic number, and it's used by the JVM to verify that a file is indeed a valid Java class file.
๐ฌ Test Case โ
java
public class T_001_CafeBabe {
@Test
public void test() throws IOException {
Class clazz = this.getClass();
String className = clazz.getName();
String classAsPath = className.replace('.', '/') + ".class";
try (var stream = clazz.getClassLoader().getResourceAsStream(classAsPath)) {
var builder = new StringBuilder();
for (byte b : stream.readNBytes(4)) {
builder.append(String.format("%02X", b));
}
Assertions.assertEquals("CAFEBABE", builder.toString());
}
}
}๐ Why This Matters โ
This is a simple but powerful illustration of how the JVM protects itself from corrupt or non-Java files. If the magic number is incorrect, the JVM will throw a ClassFormatError and refuse to load the class. It also shows the quirkiness and satire of the JVM engineers.