JVM:  Class Files

Honors Computer Systems Organization (Prof. Grishman)

Refs:  Meyer & Downing, chapter 12; Engel, chapter 9
          The Java Virtual Machine Specification, Second ed., chapter 4

Java class files must contain a great deal of information besides the actual instruction byte codes;  there is information about fields and methods, and about the constants and other classes referenced by the code.  The class file is therefore organized hierarchically, and contains a number of component tables.  It includes

The field and method entries may in turn contain zero or more attribute entries.  In particular, each method entry contains a Code attribute, whose value is the code of the method.  Attributes may also appear in the top-level (class) table.

Text information in class files is stored in UTF8 format;  this is a way of encoding (16-bit) Unicode strings so that sequences of ASCII characters are encoded one byte / character (Unicode characters outside the ASCII subset are encoded as multiple bytes).  A UTF8 constant consists of a tag (1), a 2-byte length field (giving the length in bytes), followed by the characters in UTF8 code.  A Java String constant is represented by a tag (8) and a (2-byte) index of the UTF8 constant.  Other types of constants are used to represent class names, field names, method names, etc.

The precise structure of the file is described in the Java Virtual Machine Specification as a set of C-like structure declarations;  for example, the top-level structure is

ClassFile {
        u4 magic;
        u2 minor_version;
        u2 major_version;
        u2 constant_pool_count;
        cp_info constant_pool[constant_pool_count-1];
        u2 access_flags;
        u2 this_class;
        u2 super_class;
        u2 interfaces_count;
        u2 interfaces[interfaces_count];
        u2 fields_count;
        field_info fields[fields_count];
        u2 methods_count;
        method_info methods[methods_count];
        u2 attributes_count;
        attribute_info attributes[attributes_count];
We have provided a Java Program, ReadClass, which shows how to read a class file.  You may also want to consult Bill Venners' web page, whch steps through the components of a class file :