|
Java™ by example!
|
|
|
How do I use the ClassFileTransformer in JDK 1.5 ?
The package java.lang.instrument allows you to modify class classfiles as they are loaded. On the command line, you register your own implementation of the ClassFileTransformer and this will be called by the VM every time a class is loaded. On this page, you'll find a working example of a ClassFileTransformer that will add a log statement to every method of every class that is about to be loaded. To perform the bytecode manipulation, I used the well-known Jakarta BCEL library. Two related Q&A's to achieve this kind of functionality are How do I get started with writing a dynamic proxy class? How do I get started with AspectJ? MethodInstrument.java:
Be sure to include the BCEL library in your classpath (eg. bcel-5.1.jar). A simple program to test our EntryMethodTransformer: Test.java:
Now run Test, but provide the MethodInstrument agent on the command line:
outputs:
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|