22

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.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • 1
    In addition to answers already placed here there is another great question + awnser(s) at http://stackoverflow.com/questions/3291637/alternatives-to-java-lang-reflect-proxy-for-creating-proxies-of-abstract-classes – ug_ Feb 14 '15 at 20:39

4 Answers4

30

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

Here's a tutorial.

Brian
  • 17,079
  • 6
  • 43
  • 66
  • 1
    Yes, I've looked for `Proxy`, but in all examples I've seen you have to create the instance (e.g. `Foo` instance) using the `Proxy` object. This is not acceptable in my case. I cannot modify the example code shown above. – m0skit0 Sep 11 '12 at 14:46
  • @m0skit0 If you can't insert the `Proxy` generation before the method call, then you're right, this solution won't work since you need to replace the `Foo` instance with the new `Proxy` instance. Sorry :) – Brian Sep 11 '12 at 15:40
  • Yes, actually the `Proxy` class will need to be a `Foo` factory. Thanks for your answer anyway :) – m0skit0 Sep 11 '12 at 16:39
  • @Brian the tutorial link is broken – João Matos Jun 26 '20 at 15:57
  • 1
    @JoãoMatos -- Thanks for the heads up :) I switched it over to [a newer Baeldung tutorial](https://www.baeldung.com/java-dynamic-proxies) that has Java 8+ syntax using Lambdas. – Brian Jun 29 '20 at 00:59
14

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

Gamebuster19901
  • 132
  • 1
  • 8
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
5

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.

Bhaskar
  • 7,443
  • 5
  • 39
  • 51
4

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(); 
    }                       
}
Anonymous
  • 1,726
  • 4
  • 22
  • 47
  • Thanks, but your answer is basically the same as the [accepted one](http://stackoverflow.com/a/12372266/898478) :) – m0skit0 May 30 '14 at 11:28