您的位置:首页 > 其它

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

2017-11-29 16:48 239 查看
我们在开发过程中有可能会遇不同类型的类,通过泛型的参数传到方法中,或是在别的地方得到这个参数,那么怎么去获取这个参数的实际类型是什么呢?
我们先来看一下泛型的定义,在开发过程中一般用T来表示,比如Class<T> className。
而关于泛型的使用,有两种,一种是最为面向对象的类进行开发,比如上面提到的Class<T> className ,另外一种是作为接口比如 public interface IData<T>{...}
子方法1public 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: