简体   繁体   中英

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.

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

Here's a tutorial .

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

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.

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(); 
    }                       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM