Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting method calls

Tags:

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.

like image 876
m0skit0 Avatar asked Sep 11 '12 14:09

m0skit0


People also ask

What is intercepting function calls?

(OOP) domain, is a technique of intercepting function calls at program runtime. Without directly modifying. the original code, FCI enables to undertake certain operations before and/or after the called function, or even. to replace the intercepted call.

Which is the preferred way to intercept Java calls?

Defining Interceptors The preferred way to define in Java code is by using meta-data annotations. They can be defined in the application descriptor as well, but, in that case they are not portable across Java EE servers. Some of the meta-data annotations found in the javax.

What is interception in C#?

Interception. Fody provides basic interceptors to intercept methods, properties and constructors and its feature-set is aimed towards eliminating boilerplate code.


2 Answers

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

Here's a tutorial.

like image 77
Brian Avatar answered Jan 31 '23 01:01

Brian


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

like image 23
Brian Agnew Avatar answered Jan 30 '23 23:01

Brian Agnew