java 泛型

1,如何实例化泛型

public void getData(Class type) {
      T t = newTclass(type);
}
private static  T newTclass(Class 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());

你可能感兴趣的:(java 泛型)