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

Exception or error:

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 solve:

Leave a Reply

Your email address will not be published. Required fields are marked *