问题
I have a model 'A' that have a list that can be of type 'B' or 'C' and more.
I know Polymorphism is not supported by Realm and i cant just do RealmList<RealmObject>
or RealmList<? extends RealmObject>
.
I just can't figure out how to implement this behavior with Realm.
回答1:
Polymorphism support is tracked here: https://github.com/realm/realm-java/issues/761 , but as long as it isn't implemented you have to use composition instead (https://en.wikipedia.org/wiki/Composition_over_inheritance)
In your case it would look something like this:
public interface MyContract {
int calculate();
}
public class MySuperClass extends RealmObject implements MyContract {
private A a;
private B b;
private C c;
@Override
public int calculate() {
return getObj().calculate();
}
private MyContract getObj() {
if (a != null) return a;
if (b != null) return b;
if (c != null) return c;
}
public boolean isA() { return a != null; }
public boolean isB() { return b != null; }
public boolean isC() { return c != null; }
// ...
}
来源:https://stackoverflow.com/questions/36884573/best-practice-and-how-to-implement-realmlist-that-need-to-support-different-type