Class File (binary file)

We all(Java Developers) know, in the java programming language java source files (.java) are compiled into machine readable (.class) files and the .class files have byte code.


In this section  we will look into the class file structure (class file format) .


The ClassFile Structure (As per The Java Virtual Machine)

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];
}

Magic Number: Identifying the class file format; it has the value 0xCAFEBABE.
Version of Class file :  The values of the minor_version and major_version items are the minor and major version numbers of this class file.
Constant pool : The constant pool table is where most of the literal constant values are stored. This includes values such as numbers of all sorts, strings, identifier names, references to classes and methods, and type descriptors. 
Access Flag : denote access permissions to class or interface.
This class : The value of the this_class item must be a valid index into the constant_pool. The constant pool entry at that index must be a Constant_claa_info structure representing the class or interface defined by this class file.
Super Class : Identify the superclass of this class.
Interfaces : Identify any interfaces in the class. (interfaces_count, interfaces)
Fields : Fields in the class.( fields_count, field_info fields)
Methods : Methods in the class (method_count, method_info)
Attributes : Attributes in the class  (attributes_count, attribute_info)


Simple example with binary code


Compiled with J2SE 6 and opened the class file with Binary viewer (Hexadecimal).

Some of the file Structure sections with respect to above example
Magic number : CAFEBABE
Minor version: 0000
Major Version : J2SE 6.0 = 50 (0x32 hex) – 0032
Access flag : 0001– public access



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...