Home » Android » java – Is there a way to work with generic types on Realm?-Exceptionshub

java – Is there a way to work with generic types on Realm?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Currently I’m working on an Android app which fetches for 18 types of different data references, but each of these references have its own reference class saved on Realm DB, as shown below.

There’s the reference for Type A.

public class ReferenceTypeA implements RealmModel {

    @Expose @SerializedName("codReference")
    @PrimaryKey
    private String codReference;

    @Expose @SerializedName("nameReference")
    private String nameReference;

    @Expose @SerializedName("data")
    private TypeA data;
}

And there’s the reference for TypeB.

public class ReferenceTypeB implements RealmModel {

    @Expose @SerializedName("codReference")
    @PrimaryKey
    private String codReference;

    @Expose @SerializedName("nameReference")
    private String nameReference;

    @Expose @SerializedName("data")
    private TypeB data;
}

Does Realm allow using a generic type, so I can use one Reference model and then cast data to each type of reference I’ll use at the moment? Is the code below valid? Or should I use a JSON String and then cast the result?

public class Reference implements RealmModel {

    @Expose @SerializedName("codReference")
    @PrimaryKey
    private String codReference;

    @Expose @SerializedName("nameReference")
    private String nameReference;

    @Expose @SerializedName("data")
    private T data;
}

Thanks in advance.

How to&Answers: