Reputation: 25874
I have this code
Foo foo = new Foo();
foo.callTheMethod();
Is there any way I can intercept the Foo.callTheMethod()
call without subclassing or modifying Foo
class, and without having a Foo
factory?
EDIT: sorry forgot to mention this is on Android platform.
Upvotes: 24
Views: 31097
Reputation: 17329
Use Java's Proxy
class. It creates dynamic implementations of interfaces and intercepts methods, all reflectively.
Here's a tutorial.
Upvotes: 30
Reputation: 272417
Have you considered aspect-oriented-programming and perhaps AspectJ ? See here and here for AspectJ/Android info.
Upvotes: 14
Reputation: 1773
Yes it is Possible through AspectJ. I will explain it with some code snippet:
public Aspect
{
Object around()call(* Foo.callTheMethod())
{
// do your work
return proceed();
}
}
Upvotes: 4
Reputation: 7523
Take a look at Spring AOP . You dont have to subclass your class by hand - but Spring will generate them behind the scenes and add code to do the interception.
Upvotes: 5