user3389168
user3389168

Reputation: 79

how to find out when a method from an object is called in java

I have two classes, e.g. A and B.

An instance of A creates an instance of class B. How can A become aware when an specific function from object B is called?

Object A needs to become aware whenever an specific function from object B is executed, but without changing the source code of class B. This should be done at run-time.

I guess it can be done by InvocationHandler in java, but not sure and don't know how to do it.

Upvotes: 0

Views: 98

Answers (2)

lexicore
lexicore

Reputation: 43661

Basically, you have to decorate B so that decordatedB.someMethod() first notifies a and then calls d.someMethod().

If B is an interface, it is quite easy, you do something like

final B b = new BImpl();
final B decoratedB = new B() {
  public void someMethod () {
    a.someMethodOfBisCalled();
    b.someMethod();
  }
};

If B is a class then you could use Proxy (very rough sketch):

InvocationHandler bInvocationHandler = new BInvocationHandler() {
    public Object invoke(Object proxy, Method method, Object[] args) {
       // Check this is someMethod
       // a.someMethodOfBIsCalled();
       // b.someMethod();
    }
};

B decoratedB = (B) Proxy.newProxyInstance(B.class.getClassLoader(),
    new Class[] { Foo.class }, bInvocationHandler );

There are other ways like mentioned AOP, then code instrumentation etc. etc. but I think you are well served with the above.

Upvotes: 1

jambriz
jambriz

Reputation: 1303

what about a decorator of B that notifies A ? http://en.wikipedia.org/wiki/Decorator_pattern

Upvotes: 1

Related Questions