1

我有一个模型“A”,它的列表可以是“B”或“C”等类型。我知道 Realm 不支持多态性,我不能只做RealmList<RealmObject>or RealmList<? extends RealmObject>

我只是不知道如何用 Realm 实现这种行为。

4

1 回答 1

1

多态性支持在此处跟踪:https ://github.com/realm/realm-java/issues/761 ,但只要未实现,您就必须改用组合(https://en.wikipedia.org/ wiki/Composition_over_inheritance )

在您的情况下,它看起来像这样:

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; }

  // ...
}
于 2016-04-27T08:57:19.987 回答