gpt4 book ai didi

java - Java中接口(interface)/抽象类的动态实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:42 25 4
gpt4 key购买 nike

构建接口(interface)和/或抽象类的动态实现的实际解决方案是什么?我基本上想要的是:

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

最佳答案

这是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);

关于java - Java中接口(interface)/抽象类的动态实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6914476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com