ジェネリクス型のクラス名をJavaで取得する方法
Javaでは、ジェネリクスの型パラメータをランタイム時に直接取得することはできません。理由は、Javaのジェネリクス消去メカニズムがジェネリクス型を元の型に消去するためです。
ただし、リフレクションを使用すれば、ジェネリック型のクラス名を取得できます。例を示します。
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericClass<T> {
private Class<?> genericType;
public GenericClass() {
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superClass;
Type[] typeArgs = parameterizedType.getActualTypeArguments();
if (typeArgs.length > 0) {
this.genericType = (Class<?>) typeArgs[0];
}
}
}
public Class<?> getGenericType() {
return genericType;
}
public static void main(String[] args) {
GenericClass<String> genericClass = new GenericClass<>();
Class<?> genericType = genericClass.getGenericType();
System.out.println(genericType.getName()); // 输出: java.lang.String
}
}
上の例では、汎用クラス`GenericClass`を定義し、リフレクションを利用してコンストラクタにてジェネリック型の型引数のクラス名を取得する。mainメソッドでは、`GenericClass`のインスタンスを作成し、`getGenericType()`メソッドによってジェネリック型のクラス名を取得する。
継承されたジェネリクスクラスが直線的であることに注意することが重要です。ジェネリクスを直接継承しない場合は、継承階層を再帰的に解決する必要があります。