1,如何实例化泛型
public <T>void getData(Class<T> type) {
T t = newTclass(type);
}
private static <T> T newTclass(Class<T> clazz){
T a = null;
try {
a = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return a;
}
2,如何获取java中的泛型类型
public static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
调用(通常在构造方法中调用):
Type mType = TypeUtil.getSuperclassTypeParameter(getClass());