m0skit0
m0skit0

Reputation: 25874

Intercepting method calls

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

Answers (4)

Brian
Brian

Reputation: 17329

Use Java's Proxy class. It creates dynamic implementations of interfaces and intercepts methods, all reflectively.

Here's a tutorial.

Upvotes: 30

Brian Agnew
Brian Agnew

Reputation: 272417

Have you considered aspect-oriented-programming and perhaps AspectJ ? See here and here for AspectJ/Android info.

Upvotes: 14

Anonymous
Anonymous

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

Bhaskar
Bhaskar

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

Related Questions