Reputation: 15365
Is it possible to listen to a method execution of an instance or all instances of a class, without modifying their code ? Something like:
someInstance.addMethodExecutionListener('methodName', handler);
SomeClass.addMethodExecutionListener('methodName', handler);
It would be for logging purposes...
Upvotes: 7
Views: 1225
Reputation: 4941
Depending on the environment you could use different technologies. Spring provides Aspects that you can bind to certain events (e.g. method execution).
If you are in a Java EE container managed environment you can use Interceptors for EJBs or SoapHandlers for Web Services.
Upvotes: 2
Reputation: 147154
One approach is to use the tooling API, JVMTI (replaces the separate debugging and profiling APIs).
Otherwise, you could rewrite the class files to insert your code before the method code. It's not necessarily easy. ASM is good for bytecode manipulation at a low level, but you might want to use some library (or write your own) or possibly use some "aspect" tool.
Bytecode can easily be rewritten "on disc" before loading, or at runtime using the instrumentation API and -javaagent:
on the command line.
Upvotes: 0