When I try to find examples of using Javaagent, in most cases they are examples with working with byte-code. These examples use third-party libraries, such as Javaassist.
As far as I know there are no standard means in Java to work with byte-code and in any case you'll have to resort to the libraries.
So, I tried to use these libraries in my own custom classloader before calling defineClass(). And, off course, it worked perfectly well. I could change byte-code the same way, as if I would do it with ClassFileTransformer's transform() method.
Do I understand correctly that there is another useful feature of javaagents, that in turn is their main feature? Because, first of all, javaagent gives you an Instrumentation object and the Java spec says that the instrument package is mainly used to work with byte-code. But why do I need to do that if I just can implement my own classloader (the thing I could do long before the instrument package was introduced)?
The Instrumentation API can be used at runtime without touching the code nor the compiled byte code. You can instrument every compiled java program (even without having the code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With