These days in J2EE we hear a lot about AOP and Weaving of Aspects and Injection of Code at different points in code. All this wouldn’t have been without a concept of bytecode manipulation of Java Class File while loading.
This has it roots in ClassLoading and Class file. Main benefit of java is that compile code is converted to bytecode and not any machine code which makes it easy to manipulate bytecode before it can be converted to Machine readable code
And Before Loading any class if we can change the byte code it would be same as saying ByteCode Manipulation at Runtime/LoadTime
We have lots of libraries in Java which do this BCEL / ASM / JavaAssist
Of all of them the one which is most developer friendly is JavaAssist
Before you Talk about ByteCode manipulation we should also know one ore concept that lets us to Add hook before class is loaded by JVM. Java provides concept of Agents which can be hooked with Java Command to Get callback from JVM while Class is loaded.
To Implement an agent we have to Implement ClassFileTransformer
when ever JVM loads any class it gives callback to premain method of the Agent.
Using all the concepts above here is how ByteCode manipulation is done at runtime
By hooking our agents in JVM and by manipulating Java Byte code when Loaded using Javaassist we can do our custom modifications
Attached is sample code with ant build file
Rename to zip
Any Queries mail at ashwin@linkwithweb.com
ByteCodeManipulation