Best practice and how to implement RealmList that need to support different types of objects

爱⌒轻易说出口 提交于 2019-12-24 13:56:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!