Writing a Class Loader and Bytecode Verification in Java
Implementing your own ClassLoader by overriding findClass, an integrity-checking loader that rejects tampered class files, child-first loading, parallel-capable loaders and resources, and what the bytecode verifier checks, shown with deliberately broken class files built with the ClassFile API.
kvi5hnuCode Sprout team member11 min readOn this page
Article 80 showed how the built-in class loaders find classes. Sometimes you need a loader of your own: to load classes from an unusual place (a database, an encrypted archive, the network, memory), to check them before they run, or to isolate plugins differently from the default rules. This article writes such loaders. It then looks at the second line of defence that applies to every class a loader produces, whatever its source: the bytecode verifier.
The class loader contract
java.lang.ClassLoader implements loadClass as a template method:

findLoadedClass(name)returns the class if this loader already defined it.- Otherwise the parent's
loadClassis tried. - Only if the parent throws
ClassNotFoundExceptionisfindClass(name)called.
A custom loader normally overrides only findClass: obtain the bytes for the class, then turn them into a Class with defineClass:
class MyLoader extends ClassLoader {
MyLoader(ClassLoader parent) { super("my-loader", parent); }
@Override protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] bytes = fetchBytes(name); // from wherever you like
if (bytes == null) throw new ClassNotFoundException(name);
return defineClass(name, bytes, 0, bytes.length);
}
}
Give the loader a name (the ClassLoader(String name, ClassLoader parent) constructor, Java 9), which then appears in stack traces and error messages. Pass the parent explicitly; the no-argument constructor uses the application class loader as parent.
Every class that a class defined by your loader refers to (its superclass, fields, method parameters, classes it instantiates) is requested from the same loader. In the demo, loading plugin.Greeting later loads plugin.Helper through the same loader. That is what makes a loader a self-contained namespace.
An integrity-checking loader
The demo's SealedClassLoader loads class files that carry an HMAC-SHA256 tag computed with a secret key (article 83 explains message authentication codes). In findClass it splits each file into code and tag, recomputes the tag, and compares the two with MessageDigest.isEqual, which takes the same time whether or not the tags match. Only verified bytes reach defineClass.
When one byte in Helper's constant pool is changed, Greeting still loads, because its own file is intact. Helper is only requested when get() first needs it, and then the loader refuses it. The JVM reports a NoClassDefFoundError, since a class that compiled code depends on could not be found at run time. Lazy loading means integrity errors may surface late, so a real plugin system would check all files of a plugin when it is installed.
For the same reason, code signing on the Java platform today means signed JARs (article 85): JarFile and URLClassLoader verify the signatures of signed entries and make the signers' certificates available through CodeSource.
Child-first loading
Parent-first delegation guarantees that shared types are loaded once. Sometimes the opposite is wanted: a web application or plugin should use its own version of a library even if the server has another version on its class path. Servlet containers therefore load web application classes child-first. To implement it, override loadClass itself:
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);
if (c == null && !name.startsWith("java.")) {
c = tryOwnCopy(name); // look locally first
}
if (c == null) c = super.loadClass(name, false); // then the usual parent-first path
if (resolve) resolveClass(c);
return c;
}
}
Two rules keep this safe. Never load java.* (and in practice javax.* and other platform packages) yourself, because the classes your plugin shares with the host must be identical. And hold the lock from getClassLoadingLock, because two threads may ask for the same class at once. In the demo, the child-first loader gets its own Solution class, different from the running one, while String still comes from the bootstrap loader.
Concurrency and resources
- Loaders that can load classes concurrently should call
ClassLoader.registerAsParallelCapable()in a static initializer. Then the base class uses a lock per class name instead of locking the whole loader, which avoids deadlocks between loaders that delegate to each other. - If the loader serves resources too, override
findResource(name)andfindResources(name)so thatgetResourceandgetResourceAsStreamwork for the plugin's files. defineClassalso accepts aProtectionDomain, which records theCodeSource(location and signers) of the class. With the Security Manager gone, it is mostly informational.
What defineClass refuses
defineClass performs several checks before a Class exists:
- The name passed must match the name in the bytes, or you get
NoClassDefFoundError(wrong name). - Classes in packages starting with
java.cannot be defined by any loader other than the platform's:SecurityException: Prohibited package name. - A broken file structure causes
ClassFormatError. Every class file starts with the magic number0xCAFEBABE; destroy it and the JVM reports an "incompatible magic value". Files from a newer Java version produceUnsupportedClassVersionError. - Within one loader, defining the same name twice causes
LinkageError(duplicate class definition).
Bytecode verification
A well-formed class file can still contain dangerous instructions. Bytecode is a documented format, and anyone with a hex editor, an assembler or a library such as the ClassFile API can produce class files that javac would never generate. Before a class is linked, the verifier checks its methods. Among other things it ensures that:
- local variables are assigned before they are read;
- every instruction gets operands of the right types (no adding a
Stringto anint, no treating anintas an object reference); - the operand stack never underflows or overflows its declared size;
- methods return values of their declared type;
- branches stay within the method and land on instruction boundaries;
- objects are constructed (
<init>called) before use, andfinalandprivaterules are respected; - method calls match the declared types of their receivers and arguments.
The demo builds five tiny classes with the ClassFile API, one valid and four broken, and defines them as hidden classes. The valid one computes 1 + 2. The others fail with VerifyError and messages such as "Bad local variable type" (a local read before being written), "Bad type on operand stack" and "Operand stack underflow". None of their code ever runs.
Since Java 7, class files carry a StackMapTable attribute that records the types on the stack and in the locals at branch targets, so the verifier checks the method in a single linear pass instead of inferring types (type checking rather than type inference). Compilers and bytecode libraries compute these tables; that is why the demo can drop them only because its methods have no branches.
Verification is conservative: if it accepts code, the code is type-safe, but it may reject code that would actually have been harmless, which is why javac sometimes insists that you initialize a variable it cannot prove is assigned. Classes from the platform's own runtime image are trusted and not verified by default; everything else is. The old switches to disable verification (-Xverify:none, -noverify) have been deprecated since JDK 13 and should never be used.
The program
The demo compiles a two-class plugin, seals the class files with an HMAC, loads them through SealedClassLoader, tampers with one byte and shows the rejection, demonstrates a child-first loader and the java.* restriction, runs the verifier against four broken classes, and finally destroys a magic number to get a ClassFormatError.
import java.io.*;
import java.lang.classfile.*;
import java.lang.constant.*;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import java.util.function.IntSupplier;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.tools.ToolProvider;
public class Solution {
/**
* Loads classes from "sealed" files: the class bytes followed by a 32-byte HMAC-SHA256 tag.
* Classes whose tag does not match are refused before they ever reach the JVM.
*/
static class SealedClassLoader extends ClassLoader {
private final Path dir;
private final SecretKeySpec key;
final List<String> log = new ArrayList<>();
SealedClassLoader(Path dir, byte[] key, ClassLoader parent) {
super("sealed", parent);
this.dir = dir;
this.key = new SecretKeySpec(key, "HmacSHA256");
}
@Override protected Class<?> findClass(String name) throws ClassNotFoundException {
Path file = dir.resolve(name.replace('.', '/') + ".sealed");
if (!Files.exists(file)) throw new ClassNotFoundException(name);
try {
byte[] all = Files.readAllBytes(file);
byte[] code = Arrays.copyOf(all, all.length - 32);
byte[] tag = Arrays.copyOfRange(all, all.length - 32, all.length);
if (!MessageDigest.isEqual(tag, hmac(key, code))) {
log.add("REJECTED " + name);
throw new ClassNotFoundException(name + ": integrity check failed");
}
log.add("defined " + name);
return defineClass(name, code, 0, code.length);
} catch (IOException | GeneralSecurityException e) {
throw new ClassNotFoundException(name, e);
}
}
}
/** Child-first: looks in its own directory before asking the parent (except for java.* and javax.*). */
static class ChildFirstLoader extends ClassLoader {
private final Path dir;
ChildFirstLoader(Path dir, ClassLoader parent) { super("child-first", parent); this.dir = dir; }
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);
if (c == null && !name.startsWith("java.") && !name.startsWith("javax.")) {
Path file = dir.resolve(name.replace('.', '/') + ".class");
if (Files.exists(file)) {
try {
byte[] b = Files.readAllBytes(file);
c = defineClass(name, b, 0, b.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
}
}
if (c == null) c = super.loadClass(name, false); // normal parent-first for the rest
if (resolve) resolveClass(c);
return c;
}
}
}
static byte[] hmac(SecretKeySpec key, byte[] data) throws GeneralSecurityException {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
return mac.doFinal(data);
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("loader");
try {
System.out.println("== 1. A class loader that checks integrity ==");
Path classes = dir.resolve("classes");
compile(dir, classes, "Greeting", """
package plugin;
public class Greeting implements java.util.function.Supplier<String> {
public String get() { return "Hello from " + new Helper().who(); }
}
""", "Helper", """
package plugin;
class Helper { String who() { return "a sealed plugin"; } }
""");
byte[] key = "demo key - keep real keys out of source code".getBytes(StandardCharsets.UTF_8);
Path sealed = dir.resolve("sealed");
for (String n : List.of("Greeting", "Helper")) {
byte[] code = Files.readAllBytes(classes.resolve("plugin/" + n + ".class"));
Path out = sealed.resolve("plugin/" + n + ".sealed");
Files.createDirectories(out.getParent());
var bytes = new ByteArrayOutputStream();
bytes.write(code);
bytes.write(hmac(new SecretKeySpec(key, "HmacSHA256"), code));
Files.write(out, bytes.toByteArray());
}
var loader = new SealedClassLoader(sealed, key, Solution.class.getClassLoader());
@SuppressWarnings("unchecked")
var g = (java.util.function.Supplier<String>) loader.loadClass("plugin.Greeting")
.getConstructor().newInstance();
System.out.println(g.get());
System.out.println("log: " + loader.log);
System.out.println("Greeting's loader: " + g.getClass().getClassLoader().getName()
+ ", Helper was loaded through it too");
System.out.println("\n== 2. A tampered class file is refused ==");
Path helper = sealed.resolve("plugin/Helper.sealed");
byte[] tampered = Files.readAllBytes(helper);
int idx = indexOf(tampered, "a sealed plugin".getBytes(StandardCharsets.UTF_8));
tampered[idx] = 'A'; // change one byte in the constant pool string
Files.write(helper, tampered);
var loader2 = new SealedClassLoader(sealed, key, Solution.class.getClassLoader());
try {
@SuppressWarnings("unchecked")
var g2 = (java.util.function.Supplier<String>) loader2.loadClass("plugin.Greeting")
.getConstructor().newInstance();
System.out.println("Greeting loaded fine (its file is intact); calling get() needs Helper...");
System.out.println(g2.get());
} catch (NoClassDefFoundError e) {
System.out.println("NoClassDefFoundError: " + e.getMessage());
}
System.out.println("log: " + loader2.log);
System.out.println("\n== 3. Child-first loading ==");
Path shadow = dir.resolve("shadow");
compile(dir, shadow, "Solution", """
public class Solution { public static String version() { return "child copy"; } }
""");
var childFirst = new ChildFirstLoader(shadow, Solution.class.getClassLoader());
Class<?> own = childFirst.loadClass("Solution");
System.out.println("child-first Solution == parent's Solution: " + (own == Solution.class));
System.out.println("child copy says: " + own.getMethod("version").invoke(null));
System.out.println("java.lang.String still from bootstrap: "
+ (childFirst.loadClass("java.lang.String").getClassLoader() == null));
System.out.println("\n== 4. defineClass refuses java.* ==");
try {
new ClassLoader("rogue", null) {
Class<?> define(byte[] b) { return defineClass("java.lang.Evil", b, 0, b.length); }
}.define(ClassFile.of().build(ClassDesc.of("java.lang.Evil"), cb -> {}));
} catch (SecurityException e) {
System.out.println("SecurityException: " + e.getMessage());
}
System.out.println("\n== 5. The verifier at work ==");
MethodHandles.Lookup lookup = MethodHandles.lookup();
// fun(): m = 1; n = 2; return m + n; -- valid
System.out.println("valid fun(): " + run(lookup, "Valid", code -> code
.iconst_1().istore(1).iconst_2().istore(2).iload(1).iload(2).iadd().ireturn()));
// n is never stored, but read: "uninitialized variable"
System.out.println("reads an unset local: " + run(lookup, "Uninit", code -> code
.iconst_1().istore(1).iconst_2().istore(1).iload(1).iload(2).iadd().ireturn()));
// adds a String reference to an int
System.out.println("adds a String to an int: " + run(lookup, "BadType", code -> code
.iconst_1().ldc("text").iadd().ireturn()));
// pops more than was pushed
System.out.println("stack underflow: " + run(lookup, "Underflow", code -> code
.iconst_1().iadd().ireturn()));
// returns a reference from an int method
System.out.println("wrong return type: " + run(lookup, "BadReturn", code -> code
.ldc("42").ireturn()));
System.out.println("\n== 6. Structural damage: ClassFormatError ==");
byte[] good = Files.readAllBytes(classes.resolve("plugin/Greeting.class"));
byte[] broken = good.clone();
broken[0] = 0; // destroy the CAFEBABE magic number
System.out.printf("magic: %02X%02X%02X%02X%n", good[0], good[1], good[2], good[3]);
try {
new ClassLoader("raw", Solution.class.getClassLoader()) {
Class<?> define(byte[] b) { return defineClass("plugin.Greeting", b, 0, b.length); }
}.define(broken);
} catch (ClassFormatError e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage().replaceAll(" in class file.*", ""));
}
} finally {
try (var files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete());
}
}
}
/** Builds a hidden class implementing IntSupplier whose getAsInt body is generated by the given code. */
static String run(MethodHandles.Lookup lookup, String name,
java.util.function.Consumer<CodeBuilder> body) throws ReflectiveOperationException {
byte[] bytes = ClassFile.of(ClassFile.StackMapsOption.DROP_STACK_MAPS).build(ClassDesc.of(name), cb -> cb
.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_FINAL)
.withInterfaceSymbols(ClassDesc.of("java.util.function.IntSupplier"))
.withMethodBody(ConstantDescs.INIT_NAME, ConstantDescs.MTD_void, ClassFile.ACC_PUBLIC,
c -> c.aload(0).invokespecial(ConstantDescs.CD_Object, ConstantDescs.INIT_NAME,
ConstantDescs.MTD_void).return_())
.withMethodBody("getAsInt", MethodTypeDesc.of(ConstantDescs.CD_int), ClassFile.ACC_PUBLIC, body));
try {
Class<?> c = lookup.defineHiddenClass(bytes, true).lookupClass();
return "result " + ((IntSupplier) c.getConstructor().newInstance()).getAsInt();
} catch (VerifyError e) {
return "VerifyError (" + e.getMessage().lines().findFirst().orElse("")
.replaceAll(".*Reason:\\s*", "").replaceAll("\\s*Location.*", "") + ")";
}
}
static int indexOf(byte[] hay, byte[] needle) {
outer:
for (int i = 0; i <= hay.length - needle.length; i++) {
for (int j = 0; j < needle.length; j++) if (hay[i + j] != needle[j]) continue outer;
return i;
}
return -1;
}
static void compile(Path tmp, Path out, String... namesAndSources) throws IOException {
Path src = Files.createTempDirectory(tmp, "src");
List<String> argv = new ArrayList<>(List.of("-d", out.toString()));
for (int i = 0; i < namesAndSources.length; i += 2) {
Path f = src.resolve(namesAndSources[i] + ".java");
Files.writeString(f, namesAndSources[i + 1]);
argv.add(f.toString());
}
if (ToolProvider.getSystemJavaCompiler().run(null, null, null, argv.toArray(String[]::new)) != 0)
throw new IllegalStateException("compilation failed");
}
}
== 1. A class loader that checks integrity ==
Hello from a sealed plugin
log: [defined plugin.Greeting, defined plugin.Helper]
Greeting's loader: sealed, Helper was loaded through it too
== 2. A tampered class file is refused ==
Greeting loaded fine (its file is intact); calling get() needs Helper...
NoClassDefFoundError: plugin/Helper
log: [defined plugin.Greeting, REJECTED plugin.Helper]
== 3. Child-first loading ==
child-first Solution == parent's Solution: false
child copy says: child copy
java.lang.String still from bootstrap: true
== 4. defineClass refuses java.* ==
SecurityException: Prohibited package name: java.lang
== 5. The verifier at work ==
valid fun(): result 3
reads an unset local: VerifyError (Bad local variable type)
adds a String to an int: VerifyError (Bad type on operand stack)
stack underflow: VerifyError (Operand stack underflow)
wrong return type: VerifyError (Bad type on operand stack)
== 6. Structural damage: ClassFormatError ==
magic: CAFEBABE
ClassFormatError: Incompatible magic value 16693950
Common questions
When do I really need a custom class loader?
For plugins that must be isolated or unloaded, for loading classes from non-file sources, and for generated code (article 78). Many needs are covered by URLClassLoader, ModuleLayer, or hidden classes without writing a loader.
Should I override loadClass or findClass?
findClass, unless you need child-first loading. Overriding loadClass changes delegation and is easy to get wrong: you must still delegate java.* to the parent, use getClassLoadingLock, and call findLoadedClass first.
Does encrypting class files protect my code from being copied? No. The JVM needs plain bytecode, so the decryption key and the decrypted classes are always available to someone who controls the machine. Obfuscators make reverse engineering harder; only keeping code on a server you control actually keeps it secret.
Is it safe to turn off verification for faster startup?
No. -Xverify:none is deprecated and removes a key safety check; corrupt or hostile bytecode could then crash the JVM or break memory safety. Use CDS or the AOT cache (article 80) to speed up startup instead.
Why do I get LinkageError: loader attempted duplicate class definition?
defineClass was called twice for the same name in one loader, often because two threads raced, or findLoadedClass wasn't checked. Register the loader as parallel capable and lock with getClassLoadingLock(name), or cache defined classes.
API reference
| Method | Purpose |
|---|---|
ClassLoader(String name, ClassLoader parent) | named loader with explicit parent |
findClass(String) | override to locate class bytes |
defineClass(name, bytes, off, len[, ProtectionDomain]) | turn bytes into a class |
loadClass(String, boolean) | override only for non-standard delegation |
findLoadedClass, getClassLoadingLock, resolveClass | helpers for loadClass |
ClassLoader.registerAsParallelCapable() | per-class-name locking |
findResource, findResources | serve resources |
MessageDigest.isEqual(a, b) | constant-time comparison of tags |
ClassFormatError, UnsupportedClassVersionError, VerifyError, NoClassDefFoundError, LinkageError | loading and linking failures |
ClassFile.of(StackMapsOption...), CodeBuilder | generate bytecode (used for the broken examples) |
Summary
- Extend
ClassLoader, overridefindClass, and calldefineClass; give the loader a name and an explicit parent. - Classes referenced by a class are loaded by its defining loader, so a loader defines a namespace.
- A loader can check integrity (hash, HMAC, signature) before defining a class, but it cannot make untrusted code safe.
- Override
loadClassonly for special delegation such as child-first, never loadjava.*yourself, and usegetClassLoadingLock. defineClassrejects wrong names,java.*packages, malformed files and duplicates.- The verifier checks every non-platform class for type safety, initialized locals and stack discipline; failures are
VerifyErrors. Never disable it.
Practice Questions
1. Why should a custom class loader usually override findClass rather than loadClass?
loadClass implements the delegation model, caching via findLoadedClass, and locking. Overriding findClass keeps all of that and only adds a new place to find bytes, consulted after the parent fails. Overriding loadClass is only necessary to change the delegation order, and then you have to reimplement the caching and locking correctly yourself.
2. A loader decrypts class files with a key stored in the application. Does this protect the code from being copied?
No. The loader must give plain bytecode to defineClass, so the code exists unencrypted inside the JVM. Anyone with the application can find the key, decrypt the files, or capture the bytes with a Java agent or a debugger. Encryption at rest only raises the effort slightly; legal protection and server-side execution are the real options.
3. A plugin loader is child-first for all classes, including java.util.function.Supplier, and the plugin's JAR happens to contain that class. What goes wrong?
It actually cannot define it, since java.* packages are reserved, and defineClass throws SecurityException. With a non-java shared interface, the problem is subtler: the plugin would get its own copy of the interface, the host's cast to its copy of the interface would fail with ClassCastException, because the two are different classes. Child-first loaders must delegate the shared API packages to the parent.
4. javac never produces code that reads an uninitialized local variable. Why does the JVM check for it anyway?
The JVM cannot know where a class file came from. It might have been produced by another compiler with a bug, modified with a hex editor, generated at run time, or crafted by an attacker. Reading an uninitialized slot could expose leftover data from earlier computations or let an int be used as a reference. The verifier guarantees type safety for all non-platform class files, regardless of their origin.
5. What is the difference between ClassFormatError and VerifyError?
ClassFormatError is thrown by defineClass when the bytes are not a structurally valid class file: wrong magic number, truncated data, an inconsistent constant pool. VerifyError is thrown during linking when the structure is fine but the bytecode of a method violates the type and safety rules, for example when an instruction finds operands of the wrong type on the stack.
Previous: Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces
Next: User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
Related reading
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces
- Resource Bundles in Java: Locating Bundles, Property Files and Bundle Classes
- Java Regular Expressions: Syntax, Character Classes and Quantifiers
- The Java Serialization File Format: Handles, Class Descriptors and Fingerprints

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.