Saturday, July 2, 2011

Java5 Instumentation API

The instrumentation API is for run time byte manupulation, or you can say bytecode engineering. 

we have to define our instrumentation agent which consist starting point same as main method of any java application with different arguments.

String : arguments to this agent..

Instrumentation object, instrumentation agent is a class with a special method, with a predefined signature, that the JVM will invoke before the rest of the application for you to set up any instrumentation code. Generally, instrumentation is the act of transforming classes for profiling purposes: for example, an interesting feature provided by the instrumentation framework is the ability to measure the memory usage of an object. 
 

import java.lang.instrument.Instrumentation;

public class MyAgent {
    public static void premain(String agentArguments,
            Instrumentation instrumentation) {

        MyTransFormer transformer = new MyTransFormer();
        instrumentation.addTransformer(transformer);
        Node node = new Node();
        long size = instrumentation.getObjectSize(node);
        System.out.println("size of "+ node.getClass().getSimpleName() + size);
    }
}

we have compiled the agent class and  we need to package it into a jar , we also need to create a manifest file

Premain-Class: MyAgent 
java -javaagent:myagent.jar TestMain
 
creating transformer
import java.lang.instrument.ClassFileTransformer; 
import java.security.ProtectionDomain;

public class MyTransFormer implements ClassFileTransformer {


    public MyTransFormer() {
        super();
    }


public byte[] transform(ClassLoader loader, String className,
            Class redefiningClass, ProtectionDomain domain, byte[] bytes) {
        // some changes in byte code // there are some standard API for byte
        // code modification exp: BCEL, ASM etc…
        return bytes;
    }
}


There are some links i went while reading .



  1. http://www.javalobby.org/java/forums/t19309.html#92037417

  2. http://www.cs.nuim.ie/~jpower/Research/instrument/#examples

  3. http://www.javamex.com/tutorials/memory/instrumentation.shtml

No comments:

Post a Comment

Search Ranjeet's Blog