An in-house metrics agent's ClassFileTransformer is registered in premain, yet one target class loads untransformed and nothing is logged; what in the transformer contract explains that?
answer
- failures are swallowed, not reported
- null means unchanged
- slashes, not dots
- only future definitions
- loader is null for bootstrap
basics
~20 sThe ClassFileTransformer contract fails quietly: an exception from transform is swallowed and the class loads without that change, null means unchanged, names arrive slash-separated, and only classes defined after addTransformer pass through, so earlier ones need retransformClasses.
solid answer
~40 sSeveral clauses fail silently. If `transform` throws, the JDK's transformer manager catches the `Throwable` and moves on; the class loads with whatever the other transformers produced, so a bug looks like no match. Returning `null` means "no change", so a filter that never matches also looks like success. `className` arrives in internal form, `com/acme/Foo` rather than `com.acme.Foo`, and `loader` is `null` for bootstrap classes, so a dotted name or a careless null check skips the class. `addTransformer` covers only future definitions: a class loaded before registration, or one the transformer itself depends on, is never shown, and an already loaded class needs `retransformClasses` with a retransform-capable transformer. A transformer that triggers loading of the very class it is transforming gets a `LinkageError`, swallowed like any other throw. Catch, count and log inside `transform`.
code
java · 22 linespublic final class SafeTransformer implements ClassFileTransformer {
private static final String TARGET = "com/acme/billing/InvoiceService"; // internal form
private final LongAdder failures = new LongAdder();
@Override
public byte[] transform(Module module, ClassLoader loader, String className,
Class<?> classBeingRedefined, ProtectionDomain pd,
byte[] classfileBuffer) {
if (!TARGET.equals(className)) {
return null; // null = leave the class unchanged
}
try {
byte[] out = Rewriter.addTiming(classfileBuffer); // returns a new array
System.err.println("[metrics-agent] instrumented " + className);
return out;
} catch (Throwable t) { // the JDK would swallow this silently
failures.increment();
System.err.println("[metrics-agent] failed on " + className + ": " + t);
return null;
}
}
}go deeper
Recall that an agent's ClassFileTransformer gets each class's bytes as it loads and returns either changed bytes or null for no change.
Explain the contract: internal-form names, a null loader for bootstrap classes, chained transformers, and registration covering only future class definitions.
Diagnose a silent miss by knowing that thrown exceptions are swallowed, then instrument the transformer itself and retransform classes loaded before it was registered.
Require every transformer your teams ship to report its own failures and matches, because the JDK's default is to hide both.
## The transformer contract A **`ClassFileTransformer`** is the hook a Java agent registers with `Instrumentation.addTransformer` from the `java.lang.instrument` package. The JVM calls its `transform` method with the class's bytes in class-file format **before the class is defined**, before the bytes are verified, and again when a class is redefined or, for retransform-capable transformers, retransformed. The method receives the class's module, its defining `loader`, its `className`, `classBeingRedefined` (null for a first load), the protection domain and the input `classfileBuffer`. It returns either a **new** array holding the changed class or `null` for "no change". With several transformers the calls are chained: each one's output becomes the next one's input. Most rules in that contract fail quietly when broken, which is why "registered, yet the class loads unchanged and nothing is logged" is such a common report about in-house agents. ## The silent failure paths | Cause | What the agent observes | What fixes it | |---|---|---| | `transform` throws | nothing; the class loads with the bytes the other transformers produced | catch `Throwable` inside `transform` and report it | | the filter compares a dotted name | `transform` is called but returns `null` | compare internal names such as `com/acme/billing/InvoiceService` | | the filter rejects a `null` loader | bootstrap-defined classes are skipped | treat `null` as the bootstrap loader, deliberately | | the class loaded before `addTransformer` | `transform` is never called for it | register earlier, or retransform the class | | the transformer depends on the class | the class is never offered to transformers | keep the transformer's own dependencies out of the target set | | `transform` loads the class it is transforming | a `LinkageError`, swallowed like any other throw | never load or resolve classes from inside `transform` | ## Why nothing is logged The JDK runs the chain in its own transformer manager. Each call to `transform` sits inside a `try` whose `catch (Throwable t)` block holds only a comment, so the next transformer simply runs on the unchanged buffer. The `ClassFileTransformer` documentation states the same rule as contract: throwing has the same effect as returning `null`, and that includes the dedicated `IllegalClassFormatException`. The JVM does not print the exception, does not remove the transformer and does not fail the class load. Unless the agent records its own failures, a crash in the rewriting code is indistinguishable from "this class did not match". The opposite case is loud. If a transformer **returns** malformed bytes, defining the class fails with an error such as `ClassFormatError` or `VerifyError`, and that error reaches the application. So a silent miss almost always means the transformer threw, returned `null`, or was never called. ## Which classes a transformer sees Registration timing and scope explain the remaining cases: - `addTransformer` covers **future** definitions only. Anything loaded before the call, such as JDK classes the VM loaded during start-up or everything loaded before a late load, is never offered unless the agent retransforms it. - Classes from **every loader** pass through, JDK classes included; `loader` is `null` for classes the bootstrap loader defines. - The JDK leaves out definitions of classes that any registered transformer depends on, so a transformer cannot rewrite the classes it needs in order to run. - A transformer added with `addTransformer(t)` is **retransformation-incapable**: `retransformClasses` never calls it again and only reuses its earlier output. - `removeTransformer` is not a barrier. Class loading is multi-threaded, so a removed transformer can still receive calls. ## Diagnosing it step by step 1. Log every call whose `className` matches the target before any rewriting. No log line means the class was never offered: check registration timing, the name format and whether the class loaded before the agent started. 2. Log success and failure around the rewrite with a `catch (Throwable)`. A failure line names the real bug, which the JDK would otherwise have swallowed. 3. Check whether the target was already loaded: `Instrumentation.getAllLoadedClasses()` lists it, and `-verbose:class` output shows when it loaded relative to the agent's own start-up log line. 4. If it was, register with `addTransformer(t, true)`, which needs `Can-Retransform-Classes: true` in the agent JAR, and call `retransformClasses` on it. 5. Check the `loader` argument against any loader filter: the class may come from the bootstrap loader or from a loader the filter does not expect. ## Hardening the transformer - Wrap the body of `transform` in `try` and `catch (Throwable)`, return `null` on failure and count the failure where the platform can see it. - Return `null` for every class left unchanged, and a new array for each class changed; the input buffer must not be modified. - Match on internal names and handle a `null` loader on purpose. - Resolve everything the transformer needs before registering it, and do not load classes from inside `transform`.
- If the target class was already loaded when the agent started, what exactly must the agent do?Register the transformer with `addTransformer(t, true)`, which throws `UnsupportedOperationException` unless the agent JAR declares `Can-Retransform-Classes: true`, then call `retransformClasses` on the class after checking `isModifiableClass`. The transformer is called with `classBeingRedefined` set. Methods already running keep their old bytecode; new invocations use the new one.
- Two transformers both change the same class; in what order do they run, and what does the second one receive?Retransformation-incapable transformers run before retransformation-capable ones, and within each group in registration order. The second receives the first one's returned array as its `classfileBuffer`; if the first returned `null` or threw, it receives the bytes as they were before the first one ran.
A sorting line where each station may repackage a parcel: a station that jams is simply skipped and the parcel ships as the previous station left it, and parcels that left before the station opened never reach it at all.
- If a transformer throws, the class fails to load with that exception.
- The className argument arrives as a dotted name like com.acme.Foo.
- addTransformer also transforms every class that is already loaded.
- A transformer only ever sees application classes, never bootstrap-loaded JDK classes.
- Throwing IllegalClassFormatException makes the JVM reject the class.