Skip to content

Instantly share code, notes, and snippets.

@seraphy
Created May 1, 2014 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraphy/67008303ee516178c3bf to your computer and use it in GitHub Desktop.
Save seraphy/67008303ee516178c3bf to your computer and use it in GitHub Desktop.
クラス定義時にジェネリック引数として指定されたデータ型を取得する。 "クラス定義時に明示されている場合のみ取得可能"であるため、親クラスまたはインターフェイスの実装として型指定しておく。
import java.lang.reflect.ParameterizedType;
public class GenericTypeParameterSample
extends AbstractGenericTypeParameterSample<String> {
public static void main(String[] args) {
GenericTypeParameterSample inst = new GenericTypeParameterSample();
Class<?> dataType = inst.getDataType();
System.out.println("dataType=" + dataType);
}
}
class AbstractGenericTypeParameterSample<T> {
public Class<?> getDataType() {
// クラス定義時にジェネリック引数として指定されたデータ型を取得する.
// (本クラスはabstractにして具象クラスで型パラメータを明示する.)
ParameterizedType superTyp = (ParameterizedType) getClass().getGenericSuperclass();
return (Class<?>) superTyp.getActualTypeArguments()[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment