0

Is it possible to define ONE invocationhandler (proxy) for SEVERAL objects with different interfaces ?

Because what this proxy does(all the checkings & etc.) on the objects are same (and they share a lock management table which I prefer to have it on proxy at one place),

Is there a way to do it ?

Thanks , Arian

Arian
  • 7,397
  • 21
  • 89
  • 177

2 Answers2

1

Well, the way to do that would be to have a base class representing your common IH code and then subclass it for each particular invocation.

Otherwise you can inspect the object coming in, and determine the appropriate action:

public Object invoke(Object proxy, Method method, Object[] args) {
    if (proxy instanceof InterfaceA) {
        handleInterfaceA(proxy, method, args);
    } else if (proxy instanceof InterfaceB) {
        handleInterfaceB(proxy, method, args);
    }
}

But since Java already has a class dispatch mechanism, better to use it than a bunch of IFs or a switch statement.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • The problem is that when I want to have an instance of this proxy, I have to say it's going to be proxy of a specific class with a specific interface , but now I have three classes , so I can not pass all the interfaces to instantiate a new proxy object. – Arian Nov 12 '12 at 04:15
0

Proxy.newProxyInstance specifically takes an array of interfaces, and the proxy that comes back implements all of them:

Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Foo.class, Bar.class} , new Handler())

I guess you'll have to cast the proxy to each of the different interfaces before you can call the relevant methods on it, but you always have to cast it anyway, even when you only implement one interface.

I'm not sure what the problem is; if this isn't what you meant then perhaps you can clarify?

Pete Verdon
  • 335
  • 1
  • 10