【问题标题】:Polymorphic relations in realm领域中的多态关系
【发布时间】:2017-02-23 10:15:08
【问题描述】:
IBaseA   <--- Interface
CBaseB   <--- Concrete base class

ChildA implements IBaseA{
    //fields and getters, setters
}

ChildB extends CBaseB, implements IBaseA{
    //fields and getters, setters  
}

TestClass implements RealmModel{
    private IBaseA child_obj;
}

以这种方式制作TestClass的目的是能够将任何ChildA或ChildB对象分配给TestClass.child_obj,并且仍然能够让ChildA和ChildB根据需要实现其他接口。

但是,这会导致编译时异常

Error:(12, 8) error: Type 'in.avanti_app.student_companion.realmClasses.TestClass' of field 'child_obj' is not supported

我们怎样才能达到上述目的?

【问题讨论】:

    标签: android realm realm-java


    【解决方案1】:

    Realm 不支持多态和继承。可以关注本期更新:https://github.com/realm/realm-java/issues/761

    通常我们建议使用 Composition:https://en.wikipedia.org/wiki/Composition_over_inheritance,但在您的情况下这可能并不理想,因为它看起来像这样:

    public class IBaseA extends RealmObject { ChildA childA; ChildB childB; }

    【讨论】:

      【解决方案2】:

      为每个具体类创建一个 RealmObject,将基础扁平化为 RealmObject。使用通用接口共享字段访问器。

      阅读this github comment

      Composition over inheritance for RealmObjects with Gson serialization

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多