Rewriting code after compilation

For a project at my work I needed to replace invocations of methods with my own code and still be able to call the original code in replacement. I couldn’t change the source directly as I wanted the code to be general enough to use it with other projects too.

The goal of my replacement was to add logging code to the application on byecode level. I wrote a class with a static method to do the logging and call the original method. My method had to be static to reduce the changes needed to replace the method onvocations on bytecode level. Then I put this class into my CLASSPATH. To replace the actual method invocations I used ASM. Its pretty easy to change existing class files with ASM. I will blog later about this.

When you replace method invocations like this you have to follow some rules. When the original method is static the new method has to use the same method signature. This means the the same arguments. Thanks to the way non-static methods are called in bytecode level its easy to replace them with a static method too. You just have to add the instance as first argument to the argument list of the new static method. To give you an example: the signature of the old method

(II)V

becomes

(Lfoo.bar.MyClass;II)V

for the new static method.

Inside my own static method I was able to do the logging and call the real method that got replaced. Other possible usages of this would be to change behavior of compiled code.

This entry was posted in General, Uncategorized. Bookmark the permalink.