Hello,
Java 5 comes along with a feature called “Instrumentation”.
Instrumentation allows you to access a Instrumentation-mechanism of the JVM (using a Java Agent) to gather additional information about the jvm itself such as which classes are currently loaded into the JVM, what is the platform specific object size for a specific instance (at least an
estimation) and much more…
here is a short example:
First we have to define a Class that we can load as Agent.
This class has to define a method called premain with the args shown below.
/**
*
*/
package de.tutorials;
import java.lang.instrument.Instrumentation;
/**
* @author Tom
*
*/
public class SimpleJavaAgent {
private static Instrumentation instrumentation;
public static void premain(String agentArgs, Instrumentation inst){
instrumentation = inst;
}
public static Instrumentation getInstrumentation() {
return instrumentation;
}
}
After we compiled this class we have to jar it up using this special Manifest.mf File:
Manifest-Version: 1.0
Premain-Class: de.tutorials.SimpleJavaAgent
Can-Redefine-Classes: true
Here is an example how we could use our JavaAgent to access the JVM
Instrumentation:
/**
*
*/
package de.tutorials;
/**
* @author Tom
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
Class[] loadedClasses = SimpleJavaAgent.getInstrumentation()
.getAllLoadedClasses();
for (Class clazz : loadedClasses) {
System.out.println(clazz);
}
System.out.println("Object sizes...");
Object o = new Object();
System.out.println(SimpleJavaAgent.getInstrumentation()
.getObjectSize(o));
Object oo = new Object() {
Object o;
};
System.out.println(SimpleJavaAgent.getInstrumentation().getObjectSize(
oo));
}
}
One can start this example using the java launcher in this way:
java -cp bin -javaagent:lib/simpleAgent.jar de.tutorials.Main
The Output is:
class sun.nio.cs.Surrogate
class java.util.Collections$ReverseComparator
class sun.instrument.TransformerManager
class java.nio.charset.CharsetEncoder
....
class sun.net.www.URLConnection
class [Z
class [B
class [C
class [I
class [S
class [J
class [F
class [D
Object sizes...
8
16
Sorry for my crappy english…
Kind regards and schönen Gruß
Tom