java:通过反射实现泛型的实例化(T t = new T())

public D newD(){
        D newD;
        try {
            // 通过反射获取model的真实类型
            ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class<D> clazz = (Class<D>) pt.getActualTypeArguments()[0];
            // 通过反射创建model的实例
            newD = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
       }
       return newD;
}
发布了60 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_35584878/article/details/101275076
T