1
1

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.

Genericタイプを用いるGsonパーザーを実装するメモ

1
Last updated at Posted at 2015-06-12

こんにちは、ナムです。

REST APIのCallback<T extends GeneralObject> のようにレスポンスをGenericタイプとして使用し、あとGsonを用いてレスポンスオブジェクトを習得する手順を実装しました。悩んだこととその解決についてメモにしました。

実装したいメソッド

public T parse(String raw) {
	return ...;
}

ここで、gsonを使用すると、どうするかわからなくて悩みました。

return gson.fromJson(raw, 
			xxx	// ここはなになるかわからない
				// Class<T> のインスタンスまたはTypeインスタンスとなりますが、
				// ただのGeneric Type 'T'しか持っていないから〜
			);

解決

一行で終わりそうです。

// ここはポイントです
Type type = ((ParameterizedType) this.getClass().getGenericSuperclass())
				.getActualTypeArguments()[0]; // <-- 複数のタイプの場合もありますね。

return gson.fromJson(raw, type);

わかっている方がたくさんいるかもしれませんが、javaのGenericに慣れていない僕はやはり勉強になりました。初心者の方に参考になれると嬉しいです。

では、短いですが、以上です。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?