是否可以动态添加到对象实现的接口(interface)列表中(例如 instanceof
返回 true 并且强制转换不会失败)?
我有一组对象,其类型需要在运行时动态更改。随着它们的状态发生变化,它们的更多方法/属性变得有效。目前,这是通过“暴力”方式完成的......所有成员都暴露,并且在错误的时间调用错误的成员是一个错误。理想情况下,我想使用静态类型,并将这些对象传递给需要特定接口(interface)的方法。对象实现的接口(interface)集只会增加,因此旧的引用仍然有效。
是否可以使用内置反射或通过第三方字节码操作在运行时更改对象的实现接口(interface)?
最佳答案
您可以使用 Proxy但正如评论所暗示的那样 - 这几乎总是不是最好的选择。
您最好将对象制作成多面的。
interface Interface1 {
String getI1();
}
interface Interface2 {
String getI2();
}
class Multifaceted {
String i1;
String i2;
private final Interface1 asInterface1 = new Interface1() {
@Override
public String getI1() {
return i1;
}
};
private final Interface2 asInterface2 = new Interface2() {
@Override
public String getI2() {
return i2;
}
};
public Interface1 asInterface1() {
if ( i1 == null ) {
throw new InvalidStateException("I am not ready to be one of these yet!");
}
return asInterface1;
}
public Interface2 asInterface2() {
return asInterface2;
}
}
关于java - 在运行时更改对象的实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28827801/