关于获取泛型的实际类型的方法

我们在开发过程中有可能会遇不同类型的类,通过泛型的参数传到方法中,或是在别的地方得到这个参数,那么怎么去获取这个参数的实际类型是什么呢?

我们先来看一下泛型的定义,在开发过程中一般用T来表示,比如Class<T> className。

而关于泛型的使用,有两种,一种是最为面向对象的类进行开发,比如上面提到的Class<T> className ,另外一种是作为接口比如 public interface IData<T>{...}

子方法1

public static Class getGenericClass(ParameterizedType parameterizedType, int i) {
        Object genericClass = parameterizedType.getActualTypeArguments()[i];
        if (genericClass instanceof ParameterizedType) { 
            return (Class) ((ParameterizedType) genericClass).getRawType();
        } else if (genericClass instanceof GenericArrayType) { 
            return (Class) ((GenericArrayType) genericClass).getGenericComponentType();
        } else if (genericClass instanceof TypeVariable) { 
            return (Class) getClass(((TypeVariable) genericClass).getBounds()[0], 0);
        } else {
            return (Class) genericClass;
        }
}
子方法2
public static Class getClass(Type type, int i) {
        if (type instanceof ParameterizedType) { 
            return getGenericClass((ParameterizedType) type, i);
        } else if (type instanceof TypeVariable) {
            return (Class) getClass(((TypeVariable) type).getBounds()[0], 0); 
        } else {
            return (Class) type;
        }
}
具体获取泛型类型的方法
public static <T> Class getTClass(T t) {
        Type[] params = t.getClass().getGenericInterfaces();
        Type type = params[0]; 
        Type finalNeedType;
        if (params.length > 1) {
            if (!(type instanceof ParameterizedType)) throw new IllegalStateException("没有填写泛型参数");
            finalNeedType = ((ParameterizedType) type).getActualTypeArguments()[0];
        } else {
            finalNeedType = type;
        }
        final Class clazz = getClass(finalNeedType, 0);
        return clazz;
}
 //调用
 Object reCallback = ...
 Class<T> typeof = (Class<T>) getTClass(reCallback);
 String data = ...
 new Gson().fromJson(data, typeof);

补充一个是否为java基础类型的类

public static boolean isBaseDataType(Class<?> clazz) {
        return clazz.isPrimitive() || clazz.equals(String.class) || clazz.equals(Boolean.class)
                || clazz.equals(Integer.class) || clazz.equals(Long.class) || clazz.equals(Float.class)
                || clazz.equals(Double.class) || clazz.equals(Byte.class) || clazz.equals(Character.class)
                || clazz.equals(Short.class) || clazz.equals(Date.class) || clazz.equals(byte[].class)
                || clazz.equals(Byte[].class);
}
//校验和调用
 public interface ReCallback<T>  
 ReCallback<T>  reCallback 
if(ReCallback.class.getSimpleName().equals((typeof.getSimpleName()) || isBaseDataType(typeof)){
return true;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值