Reputation: 23505
Is it possible to dynamically add to the list of interfaces implemented by an object (such that instanceof
returns true and casts don't fail)?
I have a set of objects whose types need to change dynamically during runtime. As their state changes, more of their methods/properties become valid. Currently, this is done in a "brute-force" way... all members are exposed, and calling the wrong one at the wrong time is a bug. Ideally, I would like to use static typing, and to pass these objects to methods which expect specific interfaces. The set of interfaces that an object implements will only increase, so old references would remain valid.
Is it possible to change an object's implemented interfaces at runtime, either using built-in reflection or via third-party bytecode manipulation?
Upvotes: 2
Views: 1160
Reputation: 65811
You can use a Proxy but as the comments suggest - this is almost always not the best option.
You would be better to craft you object as multifaceted.
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;
}
}
Upvotes: 2