Javassist Basic

suggest change

Javassist is a bytecode instrumentation library that allows you to modify bytecode by injecting Java code that will be converted to bytecode by Javassist and added to the instrumented class/method at runtime.

Let's write the first transformer. It takes a hypothetical class “com.my.to.be.instrumented.MyClass” and adds a log call to the instructions of each method.

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
 
public class DynamicTransformer implements ClassFileTransformer {
 
    public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
 
        byte[] byteCode = classfileBuffer;
 
        // into the transformer will arrive every class loaded so we filter 
        // to match only what we need
        if (className.equals("com/my/to/be/instrumented/MyClass")) {
 
            try {
                // retrieve default Javassist class pool
                ClassPool cp = ClassPool.getDefault();
                // get from the class pool our class with this qualified name
                CtClass cc = cp.get("com.my.to.be.instrumented.MyClass");
                // get all the methods of the retrieved class
                CtMethod[] methods = cc.getDeclaredMethods();
                for(CtMethod meth : methods) {
                    // The instrumentation code to be returned and injected
                    final StringBuffer buffer = new StringBuffer();
                    String name = meth.getName();
                    // just print into the buffer a log for example
                    buffer.append("System.out.println(\"Method " + name + " executed\" );");
                    meth.insertBefore(buffer.toString());
                }
                // create the bytecode of the class
                byteCode = cc.toBytecode();
                // remove the CtClass from the ClassPool
                cc.detach();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
 
        return byteCode;
    }
}

To make the JVM call transform as each class loads, register this transformer with an agent:

import java.lang.instrument.Instrumentation;
 
public class EasyAgent {
 
    public static void premain(String agentArgs, Instrumentation inst) {
         
        // registers the transformer
        inst.addTransformer(new DynamicTransformer());
    }
}

The last step is to register this agent class with the JVM. The easiest way is a shell option:

java -javaagent:myAgent.jar MyJavaApplication

As we can see, the agent JAR is added to the launch of any application named MyJavaApplication that is supposed to contain a class named “com.my.to.be.instrumented.MyClass” so the injected code can run. The JAR manifest must name EasyAgent as Premain-Class, or the JVM will not call premain.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents