ldiqual
ldiqual

Reputation: 15365

Is there a way to listen to another class' method execution?

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

Answers (3)

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

Tom Hawtin - tackline
Tom Hawtin - tackline

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

outis
outis

Reputation: 77400

What you're asking about is a small subset of what you can do with Aspect Oriented Programming. It's not supported in plain Java and its implementations, but it's the central reason for AspectJ.

Upvotes: 5

Related Questions