/*
* Register a listener for a given interface. If the caller has not
* been registered, then an error will be thrown.
*/
public void registerListener(Class iFace, Object o) {
CallBackHanlder handler;
if(!iFace.isAssignableFrom(o.getClass())){
throw new IllegalArgumentException("Object [" + o + "] does not " +
"implement [" + iFace.getName() +
"]");
}
synchronized (_iface2Handler) {
handler = (CallBackHanlder) _iface2Handler.get(iFace);
}
if(handler == null){
throw new IllegalArgumentException("No callback for interface [" +
iFace.getName() + "] exists");
}
handler.addListener(o);
}
/**
* @param args
*/
public static void main(String[] args) {
//Base testhandler
IndustrialDynamicProxy x=new IndustrialDynamicProxy();
//register iface, get the proxy
MyInterface caller = (MyInterface)x.generateCaller(MyInterface.class, CallBackType.RETURN_LAST);
//register the listener(real instance)
x.registerListener(MyInterface.class, new MyInterface(){
@Override
public int addTwo(int a, int b) {
System.out.println("Target method called");
return a + b;
}
});
//call the listener
int result=caller.addTwo(2, 4);
//take a look
System.out.println("addTwo(2,4):"+result);
}
/**
* An inner class to operate listeners in private
*/
static class CallBackHanlder implements InvocationHandler{
/*
* container of listeners (real instance)
* Note: work in multithread env
*/
private Set _listeners = new HashSet();
//tool of get right Type
private CallBackType _type = null;
CallBackHanlder(CallBackType type){
this._type=type;
}