How to store Java enum classes when using Realm?
From their documentation, it seems like Realm is yet to support storing enums:
Field types Realm supports the following field types: boolean, byte, short, ìnt, long, float, double, String, Date and byte[]. The integer types byte, short, int, and long are all mapped to the same type (long actually) within Realm. Moreover, subclasses of RealmObject and RealmList are supported to model relationships.
There are similar question that was asked for Objective-C and got answered here. None yet for Java though.
The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.
Enumeration (enum) in Java is a datatype which stores a set of constant values (Strings in general). You can use enumerations to store fixed values such as days in a week, months in a year etc.
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.
Without custom methods it is unfortunately slightly cumbersome at the moment, but you can store the string representation instead and convert that to/from the enum.
public enum Foo {
FOO
}
// V1: Using static methods
public class Bar1 extends RealmObject {
private String enumValue;
// Getters/setters
// Static methods to handle the enum values
public static Foo getEnum(Bar1 obj) {
return Foo.valueOf(obj.getEnumValue())
}
public static Foo setEnum(Bar1 obj, Foo enum) {
return obj.setEnumValue(enum.toString());
}
}
// V2: Use a dummy @Ignore field to create getters/setters you can override yourself.
public class Bar2 extends RealmObject {
private String enumValue;
// Dummy field
@Ignore
private String enum;
public void setEnumValue(String enumValue) {
this.enumValue = enumValue;
}
public String getEnumValue() {
return enumValue;
}
public void setEnum(Foo foo) {
setEnumValue(foo.toString());
}
public Foo getEnum() {
return Foo.valueOf(getEnumValue());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With