开发者

Dynamic implementation for interface/abstract class in Java

What's the de-facto solution for building dynamic implementation of interfaces and/or abstract classes? What I basically want is:

interface IMyEntity {
  int getValue1();
  void setValue1(int x);
}
...
class MyEntityDispatcher implements WhateverDispatcher {
  public Object handleCall(String methodName, Object[] args) {
     if(methodName.equals("getValue1")) {
       return new Integer(123);
    开发者_如何学运维 } else if(methodName.equals("setValue")) {
       ...
     }
     ...
  }
}
...
IMyEntity entity = Whatever.Implement<IMyEntity>(new MyEntityDispatcher());
entity.getValue1(); // returns 123


It's the Proxy class.

class MyInvocationHandler implements InvocationHandler {
   Object invoke(Object proxy, Method method, Object[] args)  {
     if(method.getName().equals("getValue1")) {
       return new Integer(123);
     } else if(method.getName().equals("setValue")) {
           ...
     }
     ...
  }
}

InvocationHandler handler = new MyInvocationHandler();
IMyEntity e = (IMyEntity) Proxy.newProxyInstance(IMyEntity.class.getClassLoader(),
                                                 new Class[] { IMyEntity.class },
                                                 handler);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜