0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GSON でアノテートした Enum 値の SerializedName をコードから逆引きする

Posted at
enum class SortOrder {
  @SerializedName("asc") Ascending,
  @SerializedName("desc") Descending,
}

GSON の SerializedName でアノテーションした列挙値があったとして、この値をコードから参照したくなった。

JSON としてシリアライズ・デシリアライズする値の範囲が限られていたため、コード上 enum で表現した。そして GSON での toJsonfromJson 意外の場所で、この名前を参照したくなった。
enum 自身に値を持たせてもよいけれど、 SerializedName と二重に同じ名前を管理したくない。

ということで以下のようなコードを書いた。(Enum 値限定)

inline fun <riefied T> serializedNameOf(value: T) =
    T::class.java.getField(value.toString()).getAnnotation(SerializedName::class.java).value
serializeNameOf(SortOrder.Ascending) // => "asc"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?