问题描述
我有一个模型"A",该模型的列表类型可以为"B"或"C",甚至更多.我知道Realm不支持多态,我不能只执行RealmList<RealmObject>
或RealmList<? extends RealmObject>
.
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>
.
我只是不知道如何使用Realm来实现这种行为.
I just can't figure out how to implement this behavior with Realm.
推荐答案
在此处跟踪多态支持: https://github.com/realm/realm-java/issues/761 ,但只要未实现,就必须使用组合( https://en.wikipedia.org/wiki/Composition_over_inheritance )
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; }
// ...
}
这篇关于最佳实践以及如何实现需要支持不同类型对象的RealmList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!