定义
public class MyClass<T> {
private Class<T> clazz;
public MyClass() {
Type type = this.getClass().getGenericSuperclass();
if (type instanceof ParameterizedType parameterizedType) {
if (parameterizedType.getActualTypeArguments() != null && parameterizedType.getActualTypeArguments().length > 0) {
this.clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
}
}
public String getGenericTypeName() {
return this.clazz.getName();
}
}
子类
public class MyStringClass extends MyClass<String> {
}
验证
@Test
void test() {
MyStringClass myClass = new MyStringClass();
System.out.println(myClass.getGenericTypeName());
}
输出:java.lang.String
标签:getActualTypeArguments,构造方法,clazz,MyStringClass,获取,泛型,MyClass,parameterizedType, From: https://www.cnblogs.com/jiayuan2006/p/18283827