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.
- Android: libraries arrive as JARs and AARs, and the SDK, Gradle plugins and build tools (
d8.jar, apksigner.jar) are JARs. An APK itself holds DEX bytecode (classes.dex), made from class files by D8 / R8: open it in the DEX tool.
- iOS: rare — but Kotlin Multiplatform, J2ObjC and Java-based build tools still ship JARs.
Contents
- The layout of a class file
- Versions
- The constant pool
- Descriptors and signatures
- Attributes
- Bytecode
- What javac makes of Java
- Kotlin metadata
- What to look for
- What the tool shows, and its limits
- The ClassFile library
- The Bytecode library
- The JavaDecompiler library
- 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:
| Field | Size | What it holds |
| magic | 4 | CA FE BA BE |
| minor, major | 2 + 2 | The format version (below) |
| constant pool | 2 + … | A count n, then n − 1 slots of constants; every name and literal of the class lives here |
| access flags | 2 | public final super interface abstract synthetic annotation enum module |
| this, super, interfaces | 2 + 2 + 2 + 2n | Indexes of Class constants; super is 0 only for java.lang.Object and module-info |
| fields, methods | 2 + … | Each: access flags, name, descriptor, attributes |
| attributes | 2 + … | 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:
| Tag | Kind | Content |
| 1 | Utf8 | Text in "modified UTF-8": NUL is C0 80, characters outside the BMP are two encoded surrogates |
| 3 · 4 · 5 · 6 | Integer · Float · Long · Double | The value |
| 7 · 8 | Class · String | A Utf8 index: the internal name (java/lang/String, [I), the text |
| 9 · 10 · 11 | Fieldref · Methodref · InterfaceMethodref | A Class and a NameAndType |
| 12 | NameAndType | A name and a descriptor |
| 15 · 16 | MethodHandle · MethodType | A reference kind (1–9: getField … invokeInterface) and a member; a method descriptor |
| 17 · 18 | Dynamic · InvokeDynamic | A BootstrapMethods entry and a NameAndType: a constant or a call site made at run time |
| 19 · 20 | Module · Package | Names, 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:
| Attribute | Where | What it holds |
| Code | method | max stack and locals, the bytecode, the exception table (start, end, handler, catch type or 0 for any), and its own attributes |
| LineNumberTable · LocalVariableTable · LocalVariableTypeTable | Code | Source lines; local variable names and types (generic ones in the type table) — with javac -g |
| StackMapTable | Code | The types of the locals and stack at jump targets, for the verifier (major 50+) |
| Exceptions · Signature · MethodParameters · AnnotationDefault | method | The throws clause; generic types; parameter names and flags (javac -parameters, records, enums, inner classes); an annotation element's default |
| ConstantValue | field | The value of a static final constant |
| SourceFile · SourceDebugExtension | class | The source file name; a debug map (JSR-45, Kotlin's inline function lines) |
| InnerClasses · EnclosingMethod · NestHost · NestMembers | class | Nested classes with their source names and flags; the method an anonymous or local class is in; the classes that share private access (Java 11+) |
| BootstrapMethods | class | The bootstrap method and arguments of every invokedynamic and Dynamic constant |
| Record · PermittedSubclasses | class | A record's components (Java 16); a sealed class's permitted subclasses (Java 17) |
| Module · ModulePackages · ModuleMainClass | module-info | requires, exports, opens, uses, provides |
| Runtime(In)Visible(Parameter/Type)Annotations | all | Annotations (visible ones are kept at run time) with their element values; type annotations add where in the type they apply |
| Deprecated · Synthetic | all | Markers (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:
- constants (
iconst_m1 … iconst_5, bipush, sipush, ldc of a pool constant), loads and stores (iload_1, astore 5), array access (iaload, aastore), stack shuffles (dup, dup_x1, swap — on "category 2" values a long or double counts double), arithmetic, conversions (i2l…), comparisons of longs and floats (lcmp, fcmpl / fcmpg: the l and g say whether NaN compares as −1 or 1)
- jumps: conditional (
ifeq, if_icmplt, ifnull…) with a signed 16-bit offset, goto / goto_w; tableswitch and lookupswitch, padded to a 4-byte boundary from the start of the code
- fields and calls:
getfield, putstatic, invokevirtual / special (constructors, private and super calls) / static / interface, and invokedynamic, whose call site its bootstrap method makes (lambdas, string concatenation, records' toString, pattern switches)
- objects:
new + dup + invokespecial <init>, newarray / anewarray / multianewarray, checkcast, instanceof, athrow, monitorenter / monitorexit
wide gives a load, store, ret or iinc a 16-bit slot (and iinc a 16-bit increment); jsr / ret are the subroutines of Java 1.4 compilers' finally, not allowed from major 51
7What javac makes of Java
Bytecode keeps the order of evaluation but not the shape of the source. What the decompiler recognizes:
| Source | Bytecode |
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" + b | Java 9+: invokedynamic makeConcatWithConstants with a recipe (\1 for each argument, \2 for a constant); Java 8 or -XDstringConcat=inline: a StringBuilder chain |
x -> …, Type::method | invokedynamic 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 classes | separate 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, record | an 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 c | if (!$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
- Reflection (
Class.forName, getDeclaredMethod, setAccessible, Method.invoke): code that reaches what the compiler can't see, often to call hidden platform APIs or to hide calls from a reviewer.
- Running programs (
Runtime.exec, ProcessBuilder): with a command built from input, command injection.
- Code loading (
DexClassLoader, URLClassLoader, defineClass): code that isn't in the package, possibly downloaded.
- Native code: native methods and
System.loadLibrary — the logic is in a .so (ELF tool).
- Cryptography: the algorithm strings passed to
Cipher, MessageDigest…, keys and IVs made from constants (new SecretKeySpec(KEY, …) with KEY in the class), ECB mode, java.util.Random for secrets.
- TLS: classes implementing
X509TrustManager or HostnameVerifier (read their checkServerTrusted / verify), and calls that replace the defaults.
- WebView:
addJavascriptInterface, file access settings.
- Strings: URLs, IP addresses, PEM blocks, API keys and tokens with known prefixes, long hexadecimal or Base64 constants. Compile-time constants (
static final String) are copied into every class that uses them, so the same secret can appear in many classes.
The tool reports these as facts: what is called, with which constant, and where. It runs nothing.
10What the tool shows, and its limits
- Overview: for a class, its version, flags, hierarchy, source file, debug information, Kotlin metadata, counts and a byte map (click a part to open it in the Hex tool); for a JAR, its entries, manifest, the class versions and Kotlin classes found by a scan of every class (in a worker).
- Findings: what the scan reports, grouped, each linked to the code.
- Code: the JAR's classes by package (or the class's members), the class decompiled to Java (its nested, anonymous and local classes inlined where the JAR has them), or its bytecode as
javap -c prints it. Find with /, j / b switch views, a click highlights a name, ⌘/Ctrl-click on a call opens the method.
- Class (JAR), Constant pool (searchable, with each entry's bytes), Fields & methods (flags, annotations, generic signatures), Attributes (every attribute decoded as a tree, unknown ones as bytes).
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";
| Member | What 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 · preview | The version, the release that introduced it ("Java 17", "JDK 1.2"), and whether it uses preview features. |
| constantPool | Index → { 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 · interfaces | Internal 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 · problems | The 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";
| Member | What 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_TYPES | Opcode → { 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:
- 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;
- 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;
- 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;
- 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";
| Member | What 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";
| Member | What 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.CATEGORIES | Category → { 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. |