Java class file: Difference between revisions

Content deleted Content added
@modi (talk | contribs)
 
(210 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Executable Java file format}}
In the [[Java (programming language)|Java]] programming language, source files (.java files) are compiled into class files which have a .class extension. Since Java is a [[platform-independent]] language, source code is compiled into [[Byte-code|bytecode]], which it stores in a .class file. If a source file has more than one class, each class is compiled into a separate .class file. These .class files can be loaded by any [[Java Virtual Machine]] (JVM).
{{About|the data format|classes in Java|Class (computer programming)}}
{{Infobox file format
| name = Java class file
| icon =
| logo =
| screenshot =
| mime =
| type code =
| uniform type =
| magic =
| owner = [[Sun Microsystems]]
| released =
| latest release version =
| latest release date =
| container for =
| contained by =
| extended from =
| extended to =
| standard =
| free =
| url =
}}
 
A '''Java class file''' is a [[Computer file|file]] (with the {{mono|.class}} [[filename extension]]) containing [[Java bytecode]] that can be executed on the [[Java virtual machine|Java Virtual Machine (JVM)]]. A Java class file is usually produced by a [[Java compiler]] from [[Java (programming language)|Java programming language]] [[source file]]s ({{mono|.java}} files) containing Java [[Class (programming)|classes]] (alternatively, other [[JVM languages]] can also be used to create class files). If a source file has more than one class, each class is compiled into a separate class file. Thus, it is called a {{mono|.class}} file because it contains the bytecode for a single class.
Since JVMs are available for many [[platform (computing)|platform]]s, the .class file compiled in one platform will execute in a JVM of another platform. This makes Java platform-independent.
 
JVMs are available for many [[platform (computing)|platform]]s, and a class file compiled on one platform will execute on a JVM of another platform. This makes Java applications [[cross-platform|platform-independent]].
[[As of 2006]], the modification of the class file format is being considered under [[Java Specification Request]] (JSR) 202.
 
==StructureHistory==
On 11 December 2006, the class file format was modified under [[Java Specification Request]] (JSR) 202.<ref>[http://www.jcp.org/en/jsr/detail?id=202 JSR 202] Java Class File Specification Update</ref>
===Table representation of the class file format===
 
The structure of the class file format can be visualized by a table as follows:
==File layout and structure==
 
===Sections===
There are 10 basic sections to the Java class file structure:
* '''[[Magic number (programming)|Magic Number]]''': <code>0xCAFEBABE</code>
* '''Version of Class File Format''': the minor and major versions of the class file
* '''Constant Pool''': Pool of constants for the class
* '''Access Flags''': for example whether the class is abstract, static, etc.
* '''This Class''': The name of the current class
* '''[[Superclass (computer science)|Super Class]]''': The name of the super class
* '''[[Interface (object-oriented programming)|Interfaces]]''': Any interfaces in the class
* '''Fields''': Any fields in the class
* '''[[Method (computer programming)|Method]]s''': Any methods in the class
* '''Attributes''': Any attributes of the class (for example the name of the sourcefile, etc.)
 
===Magic Number===
Class files are identified by the following 4 [[byte]] [[header (computing)|header]] (in [[hexadecimal]]): <code>CA FE BA BE</code> (the first 4 entries in the table below). The history of this [[Magic number (programming)|magic number]] was explained by [[James Gosling]] referring to a restaurant in [[Palo Alto, California|Palo Alto]]:<ref>[http://radio-weblogs.com/0100490/2003/01/28.html James Gosling private communication to Bill Bumgarner]</ref>
<blockquote>
"We used to go to lunch at a place called St Michael's Alley. According to local legend, in the deep dark past, the [[Grateful Dead]] used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place. When [[Jerry Garcia|Jerry]] died, they even put up a little Buddhist-esque shrine. When we used to go there, we referred to the place as Cafe Dead. Somewhere along the line it was noticed that this was a HEX number. I was re-vamping some file format code and needed a couple of [[Magic number (programming)|magic numbers]]: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in [[grep]]ping for 4 character hex words that fit after "CAFE" (it seemed to be a good theme) I hit on BABE and decided to use it.
At that time, it didn't seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD - it was eventually replaced by [[Java remote method invocation|RMI]]."
</blockquote>
 
===General layout===
Because the class file contains variable-sized items and does not also contain embedded file offsets (or pointers), it is typically parsed sequentially, from the first byte toward the end. At the lowest level the file format is described in terms of a few fundamental data types:
 
* '''u1''': an unsigned [[octet (computing)|8-bit]] integer
* '''u2''': an unsigned [[16-bit]] integer in [[Endianness|big-endian]] byte order
* '''u4''': an unsigned [[32-bit]] integer in big-endian byte order
* '''table''': an array of variable-length items of some type. The number of items in the table is identified by a preceding count number (the count is a u2), but the size in bytes of the table can only be determined by examining each of its items.
 
Some of these fundamental types are then re-interpreted as higher-level values (such as strings or floating-point numbers), depending on context.
There is no enforcement of word alignment, and so no padding bytes are ever used.
The overall layout of the class file is as shown in the following table.
 
{| class="wikitable"
|-
! Byte offset
! ___location in memory by byte
! valueSize
! Type or value
! item
! Description
! size
! description
|-
| 0
| 0x00000000
| 0xCA hexadecimal = 1100 1010 binary
| rowspan="4" | magic number
| rowspan="4" | 4 bytes
| u1 =<br />0xCA hex
| rowspan="4" | magic number used to identify file as conforming to the class file format
| rowspan="4" | [[magic number (programming)|magic number]] (CAFEBABE) used to identify file as conforming to the class file format
|-
| 1
| 0x00000001
| u1 =<br />0xFE hex
| 0xFE hexadecimal = 1111 1110 binary
|-
| 2
| 0x00000002
| u1 =<br />0xBA hex
| 0xBA hexadecimal = 1011 1010 binary
|-
| 3
| 0x00000003
| u1 =<br />0xBE hex
| 0xBE hexadecimal = 1011 1110 binary
|-
| 4
| 0x00000004
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | minor version number of the class file format being used
|-
| rowspan="2" | minor version number
| 5
|-
| 6
| rowspan="2" | 2 bytes
| rowspan="2" | minor version numberu2
| rowspan="2" | major version number of the class file format being used.<ref>{{Cite web|url=https://docs.oracle.com/javase/specs/jvms/se23/html/jvms-4.html#jvms-4.1-200-B.2|title = Table 4.1-A. class file format major versions}}</ref><br />
Java SE 25 = 69 (0x45 hex),<br />
Java SE 24 = 68 (0x44 hex),<br />
Java SE 23 = 67 (0x43 hex),<br />
Java SE 22 = 66 (0x42 hex),<br />
Java SE 21 = 65 (0x41 hex),<br />
Java SE 20 = 64 (0x40 hex),<br />
Java SE 19 = 63 (0x3F hex),<br />
Java SE 18 = 62 (0x3E hex),<br />
Java SE 17 = 61 (0x3D hex),<br />
Java SE 16 = 60 (0x3C hex),<br />
Java SE 15 = 59 (0x3B hex),<br />
Java SE 14 = 58 (0x3A hex),<br />
Java SE 13 = 57 (0x39 hex),<br />
Java SE 12 = 56 (0x38 hex),<br />
Java SE 11 = 55 (0x37 hex),<br />
Java SE 10 = 54 (0x36 hex),<ref>{{cite web |url=http://www.oracle.com/technetwork/java/javase/10-relnote-issues-4108729.html#Remaining |title = JDK 10 Release Notes}}</ref><br />
Java SE 9 = 53 (0x35 hex),<ref>{{cite web |url=https://bugs.openjdk.java.net/browse/JDK-8148785 |title = [JDK-8148785] Update class file version to 53 for JDK-9 - Java Bug System}}</ref><br />
Java SE 8 = 52 (0x34 hex),<br />Java SE 7 = 51 (0x33 hex),<br />Java SE 6.0 = 50 (0x32 hex),<br />Java SE 5.0 = 49 (0x31 hex),<br />JDK 1.4 = 48 (0x30 hex),<br />JDK 1.3 = 47 (0x2F hex),<br />JDK 1.2 = 46 (0x2E hex),<br />JDK 1.1 = 45 (0x2D hex).<br />For details of earlier version numbers see footnote 1 at [https://docs.oracle.com/javase/specs/jvms/se6/html/ClassFile.doc.html The JavaTM Virtual Machine Specification 2nd edition]
|-
| 7
| 0x00000005
|-
| 8
| 0x00000006
| rowspan="2" | major version number of the class file format being used
| rowspan="2" | major version number
| rowspan="2" | 2 bytes
| rowspan="2" | major version numberu2
| rowspan="2" | constant pool count, number of entries in the following constant pool table. This count is at least one greater than the actual number of entries; see following discussion.
|-
| 9
| 0x00000007
|-
| 10
| rowspan="4" | ''cpsize'' (variable)
| rowspan="4" | table
| rowspan="4" | constant pool table, an array of variable-sized constant pool entries, containing items such as literal numbers, strings, and references to classes or methods. Indexed starting at 1, containing (''constant pool count'' - 1) number of entries in total (see note).
|-
| ...
|-
| ...
|-
| ...
|-
| 10+''cpsize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | access flags, a bitmask
|-
| 11+''cpsize''
|-
| 12+''cpsize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | identifies ''this'' class, index into the constant pool to a "Class"-type entry
|-
| 13+''cpsize''
|-
| 14+''cpsize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | identifies ''super'' class, index into the constant pool to a "Class"-type entry
|-
| 15+''cpsize''
|-
| 16+''cpsize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | interface count, number of entries in the following interface table
|-
| 17+''cpsize''
|-
| 18+''cpsize''
| rowspan="4" | ''isize'' (variable)
| rowspan="4" | table
| rowspan="4" | interface table: a variable-length array of constant pool indexes describing the interfaces implemented by this class
|-
| ...
|-
| ...
|-
| ...
|-
| 18+''cpsize''+''isize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | field count, number of entries in the following field table
|-
| 19+''cpsize''+''isize''
|-
| 20+''cpsize''+''isize''
| rowspan="4" | ''fsize'' (variable)
| rowspan="4" | table
| rowspan="4" | field table, variable length array of fields
each element is a field_info structure defined in https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.5
|-
| ...
|-
| ...
|-
| ...
|-
| 20+''cpsize''+''isize''+''fsize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | method count, number of entries in the following method table
|-
| 21+''cpsize''+''isize''+''fsize''
|-
| 22+''cpsize''+''isize''+''fsize''
| rowspan="4" | ''msize'' (variable)
| rowspan="4" | table
| rowspan="4" | method table, variable length array of methods
each element is a method_info structure defined in https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.6
|-
| ...
|-
| ...
|-
| ...
|-
| 22+''cpsize''+''isize''+''fsize''+''msize''
| rowspan="2" | 2 bytes
| rowspan="2" | u2
| rowspan="2" | attribute count, number of entries in the following attribute table
|-
| 23+''cpsize''+''isize''+''fsize''+''msize''
|-
| 24+''cpsize''+''isize''+''fsize''+''msize''
| rowspan="4" | ''asize'' (variable)
| rowspan="4" | table
| rowspan="4" | attribute table, variable length array of attributes
each element is an attribute_info structure defined in https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7
|-
| ...
|-
| ...
|-
| ...
|}
 
===C programming language representationRepresentation of thea class file format===
The following is a representation of a {{mono|.class}} file as if it were a C-style struct.
The structure of the class file format can be fully described using the [[C (programming language)|C programming language]] as follows:
<syntaxhighlight lang="cpp">
struct ClassFileFormat {
u4 magicNumber;
 
u2 minorVersion;
<pre>
u2 majorVersion;
 
u2 constantPoolCount;
struct Class_File_Format {
u4 magic_number; //unsigned, 4 byte (32 bit) number that
ConstantPoolInfo[constantPoolCount - 1] constantPool;
//indicates the start of a class file
//the actual value is defined in the Java
//Virtual Machine Specification as
//0xCAFEBABE in hexadecimal, which equals
//1100 1010 1111 1110 1011 1010 1011 1110
//in binary, and 3,405,691,582 in decimal
 
u2 accessFlags;
u2 minor_version; //unsigned, 2 byte (16 bit) minor version number
u2 major_version; //unsigned, 2 byte (16 bit) major version number
 
u2 thisClass;
u2 constant_pool_count //unsigned, 2 byte (16 bit) number
u2 superClass;
//indicating the number of entries
//in the constant pool table, plus
//one
 
u2 interfacesCount;
//the constant pool table
cp_info constant_pool[constant_pool_count - 1];
u2[interfacesCount] interfaces;
 
u2 fieldsCount;
FieldInfo[fieldsCount] fields;
 
u2 access_flagsmethodsCount;
MethodInfo[methodsCount] methods;
 
u2 this_classattributesCount;
AttributeInfo[attributesCount] attributes;
u2 super_class;
}
</syntaxhighlight>
 
===The 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. All indexes, or references, to specific constants in the constant pool table are given by 16-bit (type u2) numbers, where index value 1 refers to the first constant in the table (index value 0 is invalid).
u2 interfaces_count; //unsigned, 2 byte (16 bit) number
//indicating the number of entries
//in the table of superinterfaces
//of this class
 
Due to historic choices made during the file format development, the number of constants in the constant pool table is not actually the same as the constant pool count which precedes the table. First, the table is indexed starting at 1 (rather than 0), but the count should actually be interpreted as the maximum index plus one.<ref name="jvms-4.4">{{Cite web|url=https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-4.html#jvms-4.4|title=Chapter 4. The class File Format}}</ref> Additionally, two types of constants (longs and doubles) take up two consecutive slots in the table, although the second such slot is a phantom index that is never directly used.
//the table of superinterfaces of this class
u2 interfaces[interfaces_count];
 
The type of each item (constant) in the constant pool is identified by an initial byte ''tag''. The number of bytes following this tag and their interpretation are then dependent upon the tag value. The valid constant types and their tag values are:
 
{| class="wikitable"
u2 fields_count; //unsigned, 2 byte (16 bit) number
|-
//indicating the number of entries in
! Tag byte
//the table of fields of this class
! Additional bytes
! Description of constant
! Version introduced
|-
| 1
| 2+''x'' bytes<br />(variable)
| UTF-8 (Unicode) string: a character string prefixed by a 16-bit number (type u2) indicating the number of bytes in the encoded string which immediately follows (which may be different than the number of characters). Note that the encoding used is not actually [[UTF-8]], but involves a slight modification of the Unicode standard encoding form.
| 1.0.2
|-
| 3
| 4 bytes
| Integer: a signed 32-bit [[two's complement]] number in big-endian format
| 1.0.2
|-
| 4
| 4 bytes
| Float: a 32-bit single-precision [[IEEE 754]] floating-point number
| 1.0.2
|-
| 5
| 8 bytes
| Long: a signed 64-bit two's complement number in big-endian format (takes two slots in the constant pool table)
| 1.0.2
|-
| 6
| 8 bytes
| Double: a 64-bit double-precision IEEE 754 floating-point number (takes two slots in the constant pool table)
| 1.0.2
|-
| 7
| 2 bytes
| Class reference: an index within the constant pool to a UTF-8 string containing the fully qualified class name (in ''internal format'') (big-endian)
| 1.0.2
|-
| 8
| 2 bytes
| String reference: an index within the constant pool to a UTF-8 string (big-endian too)
| 1.0.2
|-
| 9
| 4 bytes
| Field reference: two indexes within the constant pool, the first pointing to a Class reference, the second to a Name and Type descriptor. (big-endian)
| 1.0.2
|-
| 10
| 4 bytes
| Method reference: two indexes within the constant pool, the first pointing to a Class reference, the second to a Name and Type descriptor. (big-endian)
| 1.0.2
|-
| 11
| 4 bytes
| Interface method reference: two indexes within the constant pool, the first pointing to a Class reference, the second to a Name and Type descriptor. (big-endian)
| 1.0.2
|-
| 12
| 4 bytes
| Name and type descriptor: two indexes to UTF-8 strings within the constant pool, the first representing a name (identifier) and the second a specially encoded type descriptor.
| 1.0.2
|-
| 15
| 3 bytes
| Method handle: this structure is used to represent a method handle and consists of one byte of type descriptor, followed by an index within the constant pool.<ref name="jvms-4.4" />
| 7
|-
| 16
| 2 bytes
| Method type: this structure is used to represent a method type, and consists of an index within the constant pool.<ref name="jvms-4.4" />
| 7
|-
| 17
| 4 bytes
| Dynamic: this is used to specify a dynamically computed constant produced by invocation of a bootstrap method.<ref name="jvms-4.4" />
| 11
|-
| 18
| 4 bytes
| InvokeDynamic: this is used by an ''invokedynamic'' instruction to specify a bootstrap method, the dynamic invocation name, the argument and return types of the call, and optionally, a sequence of additional constants called static arguments to the bootstrap method.<ref name="jvms-4.4" />
| 7
|-
| 19
| 2 bytes
| Module: this is used to identify a module.<ref name="jvms-4.4" />
| 9
|-
| 20
| 2 bytes
| Package: this is used to identify a package exported or opened by a module.<ref name="jvms-4.4" />
| 9
|}
 
There are only two integral constant types, integer and long. Other integral types appearing in the high-level language, such as boolean, byte, and short must be represented as an integer constant.
//the table of fields of this class
field_info fields[fields_count];
 
Class names in Java, when fully qualified, are traditionally dot-separated, such as "java.lang.Object". However within the low-level Class reference constants, an internal form appears which uses slashes instead, such as "java/lang/Object".
 
The Unicode strings, despite the moniker "UTF-8 string", are not actually encoded according to the Unicode standard, although it is similar. There are two differences (see [[UTF-8]] for a complete discussion). The first is that the code point U+0000 is encoded as the two-byte sequence <code>C0 80</code> (in hex) instead of the standard single-byte encoding <code>00</code>. The second difference is that supplementary characters (those outside the [[Basic Multilingual Plane|BMP]] at U+10000 and above) are encoded using a surrogate-pair construction similar to [[UTF-16]] rather than being directly encoded using UTF-8. In this case each of the two surrogates is encoded separately in UTF-8. For example, U+1D11E is encoded as the 6-byte sequence <code>ED A0 B4 ED B4 9E</code>, rather than the correct 4-byte UTF-8 encoding of <code>F0 9D 84 9E</code>.
u2 methods_count; //unsigned, 2 byte (16 bit) number
//indicating the number of entries in
//the table of methods of this class
 
==See also==
//the table of methods of this class
{{Portal|Computer programming}}
method_info methods[methods_count];
* [[Java bytecode]]
 
==References==
{{Reflist}}
 
==Further reading==
u2 attributes_count; //unsigned, 2 byte (16 bit) number
*{{cite book
//indicating the number of
| author = [[Tim Lindholm]], Frank Yellin
//attributes in the attributes
| title = The Java Virtual Machine Specification
//table
| edition = Second
 
| publisher = Prentice Hall
//the attributes table
| year = 1999
attribute_info attributes[attributes_count];
| isbn = 0-201-43294-3
}
| url = https://docs.oracle.com/javase/specs/jvms/se6/html/ClassFile.doc.html
 
| access-date = 2008-10-13
</pre>
}} The official defining document of the [[Java virtual machine|Java Virtual Machine]], which includes the class file format. Both the first and second editions of the book are freely available [https://docs.oracle.com/javase/specs/ online for viewing and/or download].
 
==Trivia==
 
Class files are identified by the following 4 [[byte]] [[header (information technology)|header]] (in [[hexadecimal]]): <code>CA FE BA BE</code>.
 
The history of this [[Magic number (programming)|magic number]] was explained by [[James Gosling]]:
<BLOCKQUOTE>
"We used to go to lunch at a place called St Michael's Alley. According to local legend, in the deep dark past, the [[Grateful Dead]] used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place. When [[Jerry Garcia|Jerry]] died, they even put up a little Buddhist-esque shrine. When we used to go there, we referred to the place as Cafe Dead. Somewhere along the line it was noticed that this was a HEX number. I was re-vamping some file format code and needed a couple of [[Magic number (programming)|magic numbers]]: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in [[grep|grepping]] for 4 character hex words that fit after "CAFE" (it seemed to be a good theme) I hit on BABE and decided to use it. At that time, it didn't seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD - it was eventually replaced by [[Java remote method invocation|RMI]]."
</BLOCKQUOTE>
 
==References==
 
{{Java (Sun)}}
* ''The Java&trade; Virtual Machine Specification, Second Edition'' is the official defining document of the [[Java Virtual Machine]] (and consequently of the class file format) as officially specified by [[Sun Microsystems]], and is available online at [[Sun Microsystems|Sun]]'s website at [http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html], and also in printed book form as ISBN 0-201-43294-3. Both the first and second editions of the book are available for online viewing and download at [http://java.sun.com/docs/books/vmspec/ http://java.sun.com/docs/books/vmspec/]
* [http://www.jcp.org/en/jsr/detail?id=202 JSR 202] Java Class File Specification Update
* James Gosling private communication to Bill Bumgarner: http://bbum.pycs.net/2003/01/28.html
 
{{DEFAULTSORT:Class (File Format)}}
[[Category:Computer file formats]]
[[Category:Java platform]]