Created
May 1, 2014 09:38
-
-
Save seraphy/67008303ee516178c3bf to your computer and use it in GitHub Desktop.
クラス定義時にジェネリック引数として指定されたデータ型を取得する。
"クラス定義時に明示されている場合のみ取得可能"であるため、親クラスまたはインターフェイスの実装として型指定しておく。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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