0

Can I define a field with unknown type in Realm model?

Sample classes :

    public class Model1 extends RealmObject {

        @PrimaryKey
        private String _id;
        private ? field1;
    }

    public class Model2 extends RealmObject {
            @PrimaryKey
        private String _id;
    }

    public class Model3 extends RealmObject {
            @PrimaryKey
        private String _id;
    }

Now, the field1 in Model1 can be of type Model2 or Model3 which will be determined during run time. Is there any way I can achieve this?

Mayank
  • 259
  • 2
  • 16
  • 1
    Realm doens't support `Class>`. Please see the official document for more details: https://realm.io/docs/java/latest/#field-types – Dalinaum Apr 18 '17 at 08:32
  • Yeah, I know that. Asking for an similar implementation. Anyhow edited the question – Mayank Apr 18 '17 at 08:40
  • `field1` should be only one of primitive types, boxed types, specific Realm Object or RealmLists. It cannot be Model2 sometimes and Model3 sometimes. – Dalinaum Apr 18 '17 at 09:02

1 Answers1

1

No, you cannot do that. Dalinaum's comment is correct.

One way to achieve it is like;

public class Model1 extends RealmObject {
    @PrimaryKey
    private String _id;
    private Model2 model2;
    private Model3 model3;
}

public class Model2 extends RealmObject {
    @PrimaryKey
    private String _id;
}

public class Model3 extends RealmObject {
    @PrimaryKey
    private String _id;
}

and access it via;

if (model1.getModel2() == null) {
    Model2 model = model1.getModel2()
    // do something
} else {
    Model3 model = model1.getModel3()
    // do something
}
Yuta
  • 286
  • 1
  • 7