Reputation: 683
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)?
Upvotes: 3
Views: 3095
Reputation: 298163
Don’t mix up Javaagents and Instrumentation. A Java agent can use instrumentation but it doesn’t have to. It can use all other features the Java platform offers. The typical example of an agent not using instrumentation is the JMX agent. Look at what tools like JVisualVM
offer. Most of it’s features (with the exception of the profiler) are provided through the JMX agent without using instrumentation.
By the way, regarding your question about the difference between instrumentation and class loaders. A custom class loader cannot change classes loaded through the bootstrap class loader like java.lang.Object
(though you should think twice before doing this). Further, your custom class loader had to implement the original class loaders semantic to work. Otherwise, e.g. if you try to intercept loading using delegation, your class loader would miss all classes loaded when the JVM tries to resolve dependencies. And all classes loaded by another ClassLoader
created by the application (e.g. by RMI) would not get handled by your custom class loader.
So, Instrumentation adds a way to process classes independent of their ClassLoader
and (optionally) even allow to change them on demand after loading.
Upvotes: 1
Reputation: 136012
I think using javaagent is different because it is not part of your application. You can write eg a profiling agent and use it with any application.
Upvotes: 3
Reputation: 24444
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).
Upvotes: 4