← Java classes
Java class·Format guide
All tools

Java class files and JARs

A class file (.class) is what javac, kotlinc and other JVM compilers write: one class or interface, its constants, fields and methods, and the methods' code as JVM bytecode. A JAR is a ZIP of class files and resources with a META-INF/MANIFEST.MF; an AAR (an Android library) is a ZIP that holds a classes.jar. This page describes the format as the tool reads it, how the decompiler rebuilds Java, and the libraries behind it.

Contents

  1. The layout of a class file
  2. Versions
  3. The constant pool
  4. Descriptors and signatures
  5. Attributes
  6. Bytecode
  7. What javac makes of Java
  8. Kotlin metadata
  9. What to look for
  10. What the tool shows, and its limits
  11. The ClassFile library
  12. The Bytecode library
  13. The JavaDecompiler library
  14. The JavaFindings library

1The layout of a class file

Everything is big-endian. A class file is a sequence of tables, each preceded by its count:

FieldSizeWhat it holds
magic4CA FE BA BE
minor, major2 + 2The format version (below)
constant pool2 + …A count n, then n − 1 slots of constants; every name and literal of the class lives here
access flags2public final super interface abstract synthetic annotation enum module
this, super, interfaces2 + 2 + 2 + 2nIndexes of Class constants; super is 0 only for java.lang.Object and module-info
fields, methods2 + …Each: access flags, name, descriptor, attributes
attributes2 + …Each: a name (a Utf8 constant), a 4-byte length, the bytes

CAFEBABE is shared with Mach-O universal ("fat") binaries. In a class file the next four bytes are the minor and major version, and the major version is 45 or more; in a fat binary they are a 32-bit count of architectures, a small number. The tool (and ClassFile.isClassFile) takes a major version from 45 to 255 as a class file and sends a fat binary to the Mach-O tool.

2Versions

The major version says which JVM can run the class: 45 is JDK 1.1, 46–48 are 1.2–1.4, 49 is Java 5, and from there it is the release plus 44 (52 = Java 8, 55 = 11, 61 = 17, 65 = 21, 69 = 25). A minor version of 0xFFFF (with major 56 or more) marks a class that uses preview features and only runs on that exact release with --enable-preview. Android's D8 reads classes up to the Java version it supports and turns them into DEX.

3The constant pool

Constants are numbered from 1; a Long or Double takes two slots (the second is unusable). Each starts with a tag byte:

TagKindContent
1Utf8Text in "modified UTF-8": NUL is C0 80, characters outside the BMP are two encoded surrogates
3 · 4 · 5 · 6Integer · Float · Long · DoubleThe value
7 · 8Class · StringA Utf8 index: the internal name (java/lang/String, [I), the text
9 · 10 · 11Fieldref · Methodref · InterfaceMethodrefA Class and a NameAndType
12NameAndTypeA name and a descriptor
15 · 16MethodHandle · MethodTypeA reference kind (1–9: getField … invokeInterface) and a member; a method descriptor
17 · 18Dynamic · InvokeDynamicA BootstrapMethods entry and a NameAndType: a constant or a call site made at run time
19 · 20Module · PackageNames, in module-info.class only

4Descriptors and signatures

A descriptor is the erased type: B C D F I J S Z for byte, char, double, float, int, long, short, boolean, V for void, Lpkg/Name; for a class, [ before an array's element. A method's is (parameters)return: (I[Ljava/lang/String;)V is void m(int, String[]).

A signature (the Signature attribute) keeps the generics that erasure drops: <K::Ljava/lang/Comparable<TK;>;V:Ljava/lang/Object;>Ljava/lang/Object;Ljava/lang/Iterable<TV;>; is <K extends Comparable<K>, V> … implements Iterable<V>. T…; is a type variable, + / - / * are ? extends, ? super and ?, and . separates an inner class with its own arguments.

5Attributes

A JVM ignores the attributes it doesn't know, so compilers add their own (Kotlin, Scala, obfuscators). The tool decodes these and keeps the bytes of the others:

AttributeWhereWhat it holds
Codemethodmax stack and locals, the bytecode, the exception table (start, end, handler, catch type or 0 for any), and its own attributes
LineNumberTable · LocalVariableTable · LocalVariableTypeTableCodeSource lines; local variable names and types (generic ones in the type table) — with javac -g
StackMapTableCodeThe types of the locals and stack at jump targets, for the verifier (major 50+)
Exceptions · Signature · MethodParameters · AnnotationDefaultmethodThe throws clause; generic types; parameter names and flags (javac -parameters, records, enums, inner classes); an annotation element's default
ConstantValuefieldThe value of a static final constant
SourceFile · SourceDebugExtensionclassThe source file name; a debug map (JSR-45, Kotlin's inline function lines)
InnerClasses · EnclosingMethod · NestHost · NestMembersclassNested classes with their source names and flags; the method an anonymous or local class is in; the classes that share private access (Java 11+)
BootstrapMethodsclassThe bootstrap method and arguments of every invokedynamic and Dynamic constant
Record · PermittedSubclassesclassA record's components (Java 16); a sealed class's permitted subclasses (Java 17)
Module · ModulePackages · ModuleMainClassmodule-inforequires, exports, opens, uses, provides
Runtime(In)Visible(Parameter/Type)AnnotationsallAnnotations (visible ones are kept at run time) with their element values; type annotations add where in the type they apply
Deprecated · SyntheticallMarkers (older compilers; newer ones use the flags)

6Bytecode

The JVM is a stack machine: an instruction takes its operands from the operand stack and pushes its result; locals are numbered slots (a long or double takes two; the parameters, and this, come first). Opcodes are one byte, followed by their operands:

7What javac makes of Java

Bytecode keeps the order of evaluation but not the shape of the source. What the decompiler recognizes:

SourceBytecode
try { … } finally { F }F is copied before every exit of the try and of each catch; a catch-all handler runs F and rethrows (astore t; F; aload t; athrow). The exception ranges leave out the copies.
synchronized (x) { … }monitorenter, the body, monitorexit before each exit, and a catch-all that exits the monitor and rethrows
try (R r = …) { … }Java 11+: a catch of Throwable that closes r (adding a second failure as suppressed) and rethrows, and r.close() before each exit
switch (string)switch (s.hashCode()) whose cases compare with equals and set an index, then a switch on the index
switch (enumValue)switch (Outer$1.$SwitchMap$pkg$E[e.ordinal()]), an array filled in a synthetic class's static initializer
"a" + bJava 9+: invokedynamic makeConcatWithConstants with a recipe (\1 for each argument, \2 for a constant); Java 8 or -XDstringConcat=inline: a StringBuilder chain
x -> …, Type::methodinvokedynamic with LambdaMetafactory: the body is a synthetic lambda$name$n method whose first parameters are the captured variables; a method reference points at the method itself
for (T x : array)a copy of the array, its length and an index, then x = copy[i]; over an Iterable, iterator(), hasNext(), next()
inner, anonymous, local classesseparate class files (Outer$Inner, Outer$1, Outer$1Local) with the outer instance in a synthetic this$0 field and captured variables in val$x fields, passed to the constructor; Java 8 adds access$000 methods for private access
enum, recordan enum's constants are created in <clinit> with their name and ordinal; a record has private final fields, accessors and toString / hashCode / equals made by ObjectMethods
switch with patterns (Java 21)invokedynamic typeSwitch returns the index of the first matching case from a restart index; a failed guard jumps back with the next index; record patterns call the accessors inside a catch that throws MatchException
assert cif (!$assertionsDisabled && !c) throw new AssertionError(), the flag set in <clinit>

8Kotlin metadata

The Kotlin compiler marks every class with @kotlin.Metadata, which keeps what the JVM's model lacks (nullability, properties, extension functions, sealed hierarchies). Its elements: k the kind (1 class, 2 file facade, 3 synthetic class, 4 multi-file facade, 5 multi-file part), mv the metadata version, d1 a protobuf message encoded as strings — one character per byte after a leading U+0000, or 7 bits per character in older files — d2 the strings it refers to (names of functions, properties, types), xs, pn and xi, whose bits mark, among others, the JVM IR backend (bit 4), stable metadata and ABI (5) and the K2 compiler (6). The tool decodes d1 to bytes (for the Protobuf tool) and lists d2.

9What to look for

The tool reports these as facts: what is called, with which constant, and where. It runs nothing.

10What the tool shows, and its limits

Limits of the decompiler. It aims for Java that is correct before it is pretty, and checks itself against javac: on the test fixtures (Java 8 to 27, with and without -g) every class compiled with -g decompiles to source javac accepts and that behaves the same when run. Where control flow can't be structured, it prints labelled gotos (not Java, but not wrong), and a method it can't decompile at all is shown as bytecode in a comment. Known gaps: exception tables that cross each other (as R8 optimizes them) and jsr subroutines aren't structured; without debug information local variables have no generic types (a raw List), which javac may then reject; pattern switches are written with the tests typeSwitch performs rather than as case Type t; Java 8's try-with-resources stays a try/finally; nested classes are only inlined when they are in the same JAR; Kotlin-specific constructs (coroutines, inline classes) come out as the Java they compile to.

11The ClassFile library

lib/java/class-file.js parses a class file. It has no user interface and no dependencies; problems are collected in problems, and it throws only when the bytes aren't a class file at all.

import { ClassFile } from "../lib/java/class-file.js";
MemberWhat it is
ClassFile.parse(bytes)A Uint8Array or ArrayBuffer → a ClassFile; throws when it isn't one (with a word on fat Mach-O binaries).
ClassFile.isClassFile(bytes)CAFEBABE and a major version from 45 to 255.
minorVersion · majorVersion · javaVersion · previewThe version, the release that introduced it ("Java 17", "JDK 1.2"), and whether it uses preview features.
constantPoolIndex → { index, tag, tagName, offset, length, … } (null at 0 and after a Long or Double), with the referenced names filled in: value, name, className, descriptor, reference, bootstrapMethodAttrIndex…
accessFlags · flagNames · thisClass · superClass · interfacesInternal names (java/lang/String).
fields · methods[{ index, accessFlags, flagNames, name, descriptor, attributes, offset, length, signature, code / constantValue }]; signature is the parsed Signature, code the Code attribute's info.
attributes · attribute(name) · ClassFile.findAttribute(list, name)[{ name, nameIndex, offset, length, info, raw }]: info the decoded attribute (null for unknown ones), raw its bytes. The fields of each info are listed at the top of the file.
kotlinMetadata{ kind, kindName, metadataVersion, bytecodeVersion, data1, data2, extraString, packageName, extraInt, extraIntFlags, protobuf } or null.
layout · size · problemsThe parts of the file [{ offset, length, label, kind }], for a byte map; its size; what is wrong.
constantText(index) · utf8(index) · className(index)A constant as javap writes it after //; a Utf8's text; a Class constant's name.
ClassFile.parseMethodDescriptor(text){ parameters: [descriptors], returnType }.
ClassFile.typeName(descriptor, nameOf) · javaName(internal)"[Ljava/lang/String;" → "java.lang.String[]"; nameOf may shorten class names.
ClassFile.parseSignature(text, kind)kind "class", "method" or "field" → a tree of { kind: "base" | "class" | "variable" | "array" | "wildcard" } types and type parameters; signatureText and typeParametersText write them as Java.
ClassFile.flagNames(flags, context) · formatFloat(value, isFloat) · javaRelease(major)Flag words by context; Java's Float/Double.toString; the release of a major version.
const classFile = ClassFile.parse(new Uint8Array(await file.arrayBuffer()));
console.log(classFile.javaVersion, ClassFile.javaName(classFile.thisClass));
for (const method of classFile.methods) {
	const { parameters, returnType } = ClassFile.parseMethodDescriptor(method.descriptor);
	console.log(method.flagNames.join(" "), ClassFile.typeName(returnType), method.name, parameters.map(type => ClassFile.typeName(type)));
}
const strings = classFile.constantPool.filter(entry => entry && entry.tag === 8).map(entry => entry.value);

12The Bytecode library

lib/java/bytecode.js decodes a method's code; it imports class-file.js. Its listing agrees with javap -c on every instruction of the test fixtures (offsets, mnemonics, operands and comments).

import { Bytecode } from "../lib/java/bytecode.js";
MemberWhat it is
Bytecode.decode(code, classFile){ instructions, problems }; each instruction { offset, opcode, name, length, kind, wide, index, constant, local, value, target, switch: { defaultTarget, low, high, cases: [{ value, target }] }, arrayType, dimensions, count }, targets absolute.
Bytecode.OPCODES · ARRAY_TYPESOpcode → { name, format }; newarray's type codes.
Bytecode.operandText(instruction, classFile){ operands, comment } as javap prints them (#7, // Method java/io/PrintStream.println:(I)V).
Bytecode.listing(classFile, method, { details })The method as text lines: instructions, switch tables, the exception table, and with details the line numbers and local variables.
Bytecode.methodHeader(classFile, method) · isBranch(i) · successors(i)javap's declaration line; whether an instruction jumps; the offsets it may go to next.

13The JavaDecompiler library

lib/java/decompiler.js turns bytecode back into Java. It builds on the shared decompiler core (lib/decompiler-core.js: the expression IR, SSA, propagation, short-circuit conditions and the structurer that the .NET and ARM64 decompilers use) and works like the .NET one, which is also stack-based:

  1. local slots become variables by reaching definitions (one slot javac reuses for two variables gives two), named and typed from LocalVariableTable / LocalVariableTypeTable, MethodParameters, the StackMapTable or the stored values;
  2. the exception table becomes nested regions (try body, handlers); a catch-all that repeats its body at every exit is a finally (the copies are hidden), or synchronized when that body is monitorexit;
  3. each region becomes a control-flow graph by simulating the operand stack per block; ternaries and booleans are rebuilt from the stack registers; the core does SSA, propagation, dead code and structuring; an arm that only returns or throws becomes a guard if;
  4. Java idioms: string and enum switches, concatenation, lambdas and method references, anonymous classes inline, ++ / +=, array initializers, typed literals, foreach loops, try-with-resources, assert, records, enums; declarations at the narrowest block.
import { JavaDecompiler } from "../lib/java/decompiler.js";
MemberWhat it is
JavaDecompiler.decompileClass(classFile, options){ lines, stats, imports }: the compilation unit as lines { indent, html, member } (HTML spans kw ty str num cm mem fn var lbl, data-v on variables, data-m on members; member is the "name descriptor" a line belongs to). stats: { methods, decompiled, failed, goto, notes }. Options: resolveClass(internalName) → ClassFile | null for nested classes and switch maps from the same JAR; nested: false to leave nested classes out.
JavaDecompiler.decompileMethod(classFile, method, options)One body: { lines: [{ indent, html }], failed, usedGoto, notes, error }.
JavaDecompiler.text(lines) · plain(html)The source as text, four spaces per level; a line's text.
const classes = new Map(jarClasses.map(classFile => [classFile.thisClass, classFile]));
const result = JavaDecompiler.decompileClass(classes.get("com/example/Main"), { resolveClass: name => classes.get(name) || null });
console.log(JavaDecompiler.text(result.lines), result.stats);

14The JavaFindings library

lib/java/findings.js lists what a review looks at (section 9); it reads the instructions with bytecode.js.

import { JavaFindings } from "../lib/java/findings.js";
MemberWhat it is
JavaFindings.scan(classFile)[{ category, title, detail, member, offset }]: category reflection exec loading native crypto tls webview network storage string; the method and bytecode offset of a call.
JavaFindings.CATEGORIESCategory → { label, description }.
JavaFindings.stringKind(text)What a string looks like (a URL, an IP address, a PEM block, an AWS / Google / Stripe-style key, a JWT, hex or Base64 of a key's size), or null.