java 反射 如何获得子类继承的父类泛型参数
2014-02-18 07:07
232 查看
废话不多说,把下面这个方法跑一下,就OK了,参数是子类Class,返回值是子类继承父类时给父类传入的泛型参数,该方法假定父类只有一个泛型参数,否则抛出异常。
public static Class getGenericSuperclassBounds(Class childClass){
Type type = childClass.getGenericSuperclass();
while(!(type instanceof Class)){
if(type instanceof WildcardType){
type = ((WildcardType)type).getUpperBounds()[0];
}
else if(type instanceof TypeVariable<?>){
type = ((TypeVariable<?>)type).getBounds()[0];
}
else if(type instanceof ParameterizedType){
ParameterizedType ptype = (ParameterizedType)type;
Type[] types = ptype.getActualTypeArguments();
if(types==null||types.length==0){
return Object.class;
}
if(types.length>1){
throw new RuntimeException(childClass.getName()+"继承的泛型"+ptype+"的实参数量多于1个");
}
type = ptype.getActualTypeArguments()[0];
}
else if(type instanceof GenericArrayType ){
type = ((GenericArrayType)type).getGenericComponentType();
}
}
return (Class)type;
}
public static Class getGenericSuperclassBounds(Class childClass){
Type type = childClass.getGenericSuperclass();
while(!(type instanceof Class)){
if(type instanceof WildcardType){
type = ((WildcardType)type).getUpperBounds()[0];
}
else if(type instanceof TypeVariable<?>){
type = ((TypeVariable<?>)type).getBounds()[0];
}
else if(type instanceof ParameterizedType){
ParameterizedType ptype = (ParameterizedType)type;
Type[] types = ptype.getActualTypeArguments();
if(types==null||types.length==0){
return Object.class;
}
if(types.length>1){
throw new RuntimeException(childClass.getName()+"继承的泛型"+ptype+"的实参数量多于1个");
}
type = ptype.getActualTypeArguments()[0];
}
else if(type instanceof GenericArrayType ){
type = ((GenericArrayType)type).getGenericComponentType();
}
}
return (Class)type;
}
相关文章推荐
- java反射获得泛型参数getGenericSuperclass():获取到父类泛型的类型
- java反射获得父类泛型参数
- java中如何让一个子类不能调用从父类继承的方法
- 思想:java中,父类的方法中传入的形参的数据类型是泛型,子类的方法的形参想只要一种确定的数据类型,子类该如何做呢?
- 一、获取子类DAO继承父类DAO的泛型参数类型的Class对象
- java反射获得泛型参数GETGENERICSUPERCLASS()
- java反射获得泛型参数
- Java 使用反射观察子类是否继承了父类的私有方法
- java反射获得泛型参数getGenericSuperclass()
- java之中的四种访问权限和子类如何继承父类特性
- 如何反射获得父类的泛型类型
- 父类通过反射获得子类的class泛型类型
- Java 泛型学习(三)通过反射获得泛型的实际类型参数
- JAVA中通过反射获得泛型的实际参数
- 如何获取java中泛型参数的实际类型--反射获取
- java反射,获得Class是否为基本数据类型,是否其他类的父类。获得泛型。
- java 中子类如何实现对父类私有域的继承
- java_通过反射获得泛型的实际类型参数
- Java父类取得子类传递的泛型参数Class类型
- DAO中,如何获取子类带泛型的父类的参数