Is there a way to get the serialized name out of a...
# reflect
j
Is there a way to get the serialized name out of an enum value without using reflection? For now I’ve been doing this but I honestly don’t know if that’s a good thing to do
Copy code
enum class DeviceAttributeType {
    ...
    @SerializedName("waterOverflowIndication")
    WATER_OVERFLOW_INDICATION,

    @SerializedName("windowCoverLiftPercentage")
    WINDOW_COVER_LIFT_PERCENTAGE;
    ...
    override fun toString() = DeviceAttributeType::class.java
        .getField(name)
        .getAnnotation(SerializedName::class.java)
        ?.value ?: super.toString()
}
i
afaik reflection is the only way. we’ve been using it as well. https://stackoverflow.com/questions/24114382/gson-how-to-get-serialized-name
j
A KSP plugin writing automatically an overriding of the toSting method + a function to get an enum value from the serialized string would be nice 🤔
like APT, KSP can't modify existing classes, but you can write the short
override fun toString() = <generated function>()
yourself
j
I did write a processor yes, but didn’t published it yet, I’ll have a look at this project, thanks 🙂
564 Views