And*_*lov 11 java proxy dynamic dynamic-proxy
什么是构建接口和/或抽象类的动态实现的事实上的解决方案?我基本上想要的是:
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
Run Code Online (Sandbox Code Playgroud)
Joa*_*uer 18
这是Proxy班级.
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10223 次 |
| 最近记录: |