领域中的多态关系

时间:2017-02-23 10:15:09

标签: android realm realm-java

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

我们如何才能达到上述目的?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

阅读this github comment

Composition over inheritance for RealmObjects with Gson serialization