Sub topic 2
Inside a .class file
This chapter assumes you can compile and run Java programs with javac and java, and that you know classes, methods, static members, and exceptions. The JVM does not run .java files. It runs .class files, which have a fixed binary layout. Knowing that layout explains the errors the JVM reports when it rejects a file, and it makes the rest of the tutorial concrete.
One class, one file
For every class, interface, enum, or record, javac writes one .class file. A nested class gets its own file too, named like Outer$Inner.class. The file contains no machine code for a specific CPU. It holds a description of one type: its name, its supertypes, its fields, its methods, and the bytecode of each method.
Compile the example class from the spine:
public class MathOps {
public static int add(int a, int b) {
return a + b;
}
}$ javac MathOps.java
$ ls -l MathOps.classThe resulting file is a few hundred bytes. Almost all of it is names and descriptors. The bytecode for add is only four bytes.
The top-level layout
A class file is a sequence of fixed-order structures. All multi-byte numbers are stored big-endian. The specification calls the sizes u1, u2, and u4, meaning 1, 2, and 4 unsigned bytes.
| Order | Item | Size | Purpose |
|---|---|---|---|
| 1 | `magic` | u4 | Always `0xCAFEBABE`. Identifies the file as a class file. |
| 2 | `minor_version` | u2 | Almost always 0 in modern files. |
| 3 | `major_version` | u2 | The class file format version. |
| 4 | `constant_pool_count` and `constant_pool` | u2, then entries | Shared table of names, types, and literals. |
| 5 | `access_flags` | u2 | Bit flags such as public, final, interface, abstract. |
| 6 | `this_class` | u2 | Constant pool index of this class's name. |
| 7 | `super_class` | u2 | Constant pool index of the superclass (0 only for `java.lang.Object`). |
| 8 | `interfaces` | u2 count, then u2 indexes | Directly implemented interfaces. |
| 9 | `fields` | u2 count, then entries | Field declarations. |
| 10 | `methods` | u2 count, then entries | Method declarations, including bytecode. |
| 11 | `attributes` | u2 count, then entries | Class-level extra information. |
The structure has no section offsets. A reader must parse each section in order, because the size of one section decides where the next starts. The JVM parses the file this way, and so does every tool that reads class files.
Reading the header yourself
The first eight bytes hold the magic number and both version numbers. This program reads them:
import java.io.DataInputStream;
import java.io.FileInputStream;
public class ClassHeader {
public static void main(String[] args) throws Exception {
try (DataInputStream in = new DataInputStream(new FileInputStream("MathOps.class"))) {
int magic = in.readInt();
int minor = in.readUnsignedShort();
int major = in.readUnsignedShort();
System.out.printf("magic=%08X minor=%d major=%d%n", magic, minor, major);
}
}
}DataInputStream reads big-endian values, which matches the class file format, so no byte swapping is needed. Compiled with Java 11, the output is:
magic=CAFEBABE minor=0 major=55You can see the same bytes with a hex dump:
$ xxd -l 8 MathOps.class
00000000: cafe babe 0000 00370x37 is 55 in decimal.
Version numbers
The major version identifies the Java release whose class file format the compiler targeted.
| Java release | Major version |
|---|---|
| 8 | 52 |
| 9 | 53 |
| 10 | 54 |
| 11 | 55 |
A JVM accepts class files up to its own major version and rejects anything newer. A Java 11 JVM that loads a class compiled by a newer compiler fails with an error like this:
java.lang.UnsupportedClassVersionError: MathOps has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0This error is one of the most common ones you will see in practice. The fix is to run on a newer JVM, or to compile for an older target with javac --release 11. If the first four bytes are not 0xCAFEBABE, the JVM throws ClassFormatError with the message "Incompatible magic value". A truncated download or a text file renamed to .class triggers it.
Access flags
The access_flags field is a bit mask. The most important bits for classes are these:
| Flag | Value | Meaning |
|---|---|---|
| `ACC_PUBLIC` | 0x0001 | Declared `public`. |
| `ACC_FINAL` | 0x0010 | Declared `final`. |
| `ACC_SUPER` | 0x0020 | Set by modern compilers on every class, for `invokespecial` semantics. |
| `ACC_INTERFACE` | 0x0200 | This is an interface. |
| `ACC_ABSTRACT` | 0x0400 | Declared `abstract`, or an interface. |
| `ACC_SYNTHETIC` | 0x1000 | Generated by the compiler, not in the source. |
| `ACC_ENUM` | 0x4000 | Declared as an `enum`. |
MathOps is public, so its flags are 0x0001 | 0x0020 = 0x0021. Fields and methods have their own access_flags with a different set of bits. For example, 0x0008 means static on a field or method.
Looking at the whole file with javap
javap -c shows only bytecode. To see the structure described above, use -v (verbose):
$ javap -v MathOpsThe output begins with a summary that matches the table above:
minor version: 0
major version: 55
flags: (0x0021) ACC_PUBLIC, ACC_SUPER
this_class: #2 // MathOps
super_class: #3 // java/lang/Object
interfaces: 0, fields: 0, methods: 2, attributes: 1The exact # numbers can differ between compiler versions. The format is always the same.
Two things in this output surprise many readers. First, methods: 2, although you wrote only one method. The compiler added a default constructor, named <init>. Second, this_class and super_class are not strings. They are indexes into the constant pool, where the actual names live.
Fields and methods
Each field and method entry has the same shape: access flags, a name index, a descriptor index, and a list of attributes. The name and descriptor are both constant pool indexes.
A descriptor is a compact string that encodes a type:
| Descriptor | Type |
|---|---|
| `I` | `int` |
| `J` | `long` |
| `Z` | `boolean` |
| `D` | `double` |
| `V` | `void` (return type only) |
| `Ljava/lang/String;` | `java.lang.String` |
| `[I` | `int[]` |
A method descriptor lists the parameter types in parentheses, then the return type. So add(int, int) returning int has the descriptor (II)I, and main(String[]) has the descriptor ([Ljava/lang/String;)V. Method names are not enough to identify a method in a class file. The JVM identifies a method by name plus descriptor. That is how overloading works at this level: add(II)I and add(JJ)J are separate entries.
Attributes
Attributes attach extra data to a class, field, or method. Each one has a name and a length, so a JVM can skip any attribute it does not recognize. Common ones include:
Code: the bytecode of a method, plusmax_stack,max_locals, and an exception table. This is whereiload_0,iload_1,iadd, andireturnare stored.LineNumberTable: maps bytecode offsets to source lines. Stack traces use it.SourceFile: the name of the original.javafile.ConstantValue: the value of astatic finalfield with a compile-time constant. The initialization chapter returns to this one.InnerClasses,NestHost, andNestMembers: describe nested classes. Java 11 added the nest attributes so nested classes can access each other's private members without generated bridge methods.
javac omits some attributes by default. For example, local variable names appear in LocalVariableTable only if you compile with -g.
The constant pool in one paragraph
Almost everything in the file refers to names indirectly. A method entry does not contain the string add. It contains the index of a Utf8 entry in the constant pool that holds those characters. Indexes start at 1, and index 0 is never valid. constant_pool_count is one more than the number of slots, and long and double constants take two slots. Entries also hold class references, method references, and literal numbers and strings. The next chapter covers them in detail.
Common mistakes
- Reading class files with a little-endian assumption. The format is big-endian. Use
DataInputStreamorByteBufferin its default byte order. - Treating the major version as the Java version. The major version is 55 for Java 11, not 11. The offset from the release number is 44 for Java 2 and later.
- Expecting a
.classfile to carry local variable names. Without-g, they are gone, andjavapshows onlyarg0-style placeholders or slot numbers. - Assuming
javapshows source. It decodes the file structure and bytecode, and nothing from the original source beyond the attributes the compiler chose to keep.
Exercise
You run xxd -l 8 Foo.class and see cafe babe 0000 0034. Which Java release did the compiler target, and what happens if you run this class on a Java 8 JVM and on a Java 11 JVM?
Show answer
0x34 is 52, which is the major version for Java 8. A Java 8 JVM accepts it because its supported maximum is 52. A Java 11 JVM also accepts it, because a JVM runs class files up to its own major version (55) and older ones as well. Neither JVM throws UnsupportedClassVersionError. The error appears only when the class file's major version is higher than the JVM supports, for example running a version 55 class on Java 8.
Exercise
A class file contains a method whose descriptor is (ILjava/lang/String;)Z. Write the Java method signature this describes, using any method name.
Show answer
boolean check(int a, String b). The descriptor lists an int and a String as parameters, and Z as the return type means boolean. The parameter names do not appear in the descriptor.