tinycodinglm / lang /lang-0022.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
4.48 kB
opencode trace
System You are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API.

You are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API.

User

Explain the core Instrumentation API methods: addTransformer, removeTransformer, redefineClasses, and retransformClasses. When do you use each one? Provide code examples.

Assistant

The Instrumentation API Core Methods

The Instrumentation interface provides the complete lifecycle management for bytecode transformation.

1. addTransformer() / removeTransformer()

Transformers intercept class loading:

java
import java.lang.instrument.Instrumentation;
import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

public class TransformerDemo {
    private static Instrumentation inst;
    private static ClassFileTransformer transformer;

    public static void init(Instrumentation instrumentation) {
        inst = instrumentation;

        // Simple form - called for ALL class loads
        transformer = new MyTransformer();
        inst.addTransformer(transformer);

        // Retransformation-capable form
        ClassFileTransformer retransformer = new RetransformTransformer();
        inst.addTransformer(retransformer, true); // true = canRetransform
    }

    public static void remove() {
        inst.removeTransformer(transformer);
    }
}

2. redefineClasses()

Replaces the bytecode of an already-loaded class. Cannot add/remove fields or methods:

java
public class RedefineExample {
    public static void redefineClass(Instrumentation inst, Class<?> targetClass) {
        if (!inst.isRedefineClassesSupported()) {
            throw new UnsupportedOperationException("Redefine not supported");
        }
        try {
            byte[] newBytes = Files.readAllBytes(
                Path.of("build/classes/NewVersion.class"));
            ClassDefinition def = new ClassDefinition(targetClass, newBytes);
            inst.redefineClasses(def);
            System.out.println("Class redefined successfully");
        } catch (Exception e) {
            System.err.println("Redefinition failed: " + e.getMessage());
        }
    }
}

3. retransformClasses()

Triggers the transformer chain on already-loaded classes:

java
public class RetransformExample {
    public static void retransformLoadedClasses(Instrumentation inst) {
        for (Class<?> cls : inst.getAllLoadedClasses()) {
            String name = cls.getName();
            if (name.startsWith("com.example.service.")) {
                try {
                    System.out.println("Retransforming: " + name);
                    inst.retransformClasses(cls);
                } catch (UnmodifiableClassException e) {
                    System.err.println("Cannot retransform: " + name);
                }
            }
        }
    }
}

4. Complete Lifecycle Example

java
public class InstrumentationManager {
    private final Instrumentation inst;
    private final Set<String> instrumentedClasses = ConcurrentHashMap.newKeySet();
    private ClassFileTransformer activeTransformer;

    public InstrumentationManager(Instrumentation inst) {
        this.inst = inst;
    }

    public void start() {
        activeTransformer = new TimingTransformer();
        inst.addTransformer(activeTransformer, true);
    }

    public void instrument(Class<?>... classes) {
        try {
            inst.retransformClasses(classes);
            for (Class<?> c : classes) {
                instrumentedClasses.add(c.getName());
            }
        } catch (UnmodifiableClassException e) {
            throw new RuntimeException(e);
        }
    }

    public void stop() {
        if (activeTransformer != null) {
            inst.removeTransformer(activeTransformer);
        }
        instrumentedClasses.clear();
    }
}

Key differences: redefineClasses() replaces bytecode entirely, retransformClasses() re-runs the transformer chain, and addTransformer(transformer, true) is required for retransform support.