Reputation: 7497
Is it possible to spy on the method calls being made to instances of a Java class. I know I could achieve this using java.lang.reflect.InvocationHandler
. I'm wondering if there are other easier ways which don't involve modifying the source code of the classes?
EDIT:
For example java.util.HashMap
. The source code for this class is not available - at least for me it's not when running under Oracle's JDK. How would I intercept the calls made to the put(...) method. I would like to inspect the parameters in the call.
Upvotes: 1
Views: 1072
Reputation: 629
You can try JMSPY. Jmspy is a java library that allows recording of java methods invocations, saving data into a file called snapshot and analyzing it using jmspy viewer.
Upvotes: 1
Reputation: 6040
You might do this with Aspect Oriented Programming. You're just have to declare pointcuts of your code, which you're want to 'spy'. In a few words - you're might declare annotations, put them above methods signatures, and all annotated methods might been modified by compiler in a compile time (or been modified in time of loading bytecode to jvm) without needs to modify their source code.
AspectJ is useful for this.
Upvotes: 4
Reputation: 5619
I would suggest studying aspect oriented programming which allows separation of cross-cutting concerns (logging etc.) .
This way, specifying pointcuts for your methods you may "spy" on the methods.
Upvotes: 0
Reputation: 1539
Let me rephrase your problem: You want to execute your own code every time a non-static method call to a specific class is executed. I also assume you have full access to the JVM environment.
Take a look at JMX Beans. These beans are interfaces to the behaviour of the Java Virtual Machine.
Also look at the Java Agent specification for modifying existing applications where you do not have access to the MAIN method.
Upvotes: 1