zoukankan      html  css  js  c++  java
  • java 生成泛型的参数的实例 T t=new T()

    方法1

    ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class clazz = (Class<T>) ptype.getActualTypeArguments()[0];
    T o = (T) clazz.newInstance();

    方法2

    public class BaseViewModel<M extends Model> implements ViewModel {
    
        protected M model;
    
        private M createModel() {
    
            try {
                Type superClass = getClass().getGenericSuperclass();
                Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
                Class<?> clazz = getRawType(type);
                return (M) clazz.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        // type不能直接实例化对象,通过type获取class的类型,然后实例化对象
        public static Class<?> getRawType(Type type) {
            if (type instanceof Class) {
                return (Class) type;
            } else if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                Type rawType = parameterizedType.getRawType();
                return (Class) rawType;
            } else if (type instanceof GenericArrayType) {
                Type componentType = ((GenericArrayType) type).getGenericComponentType();
                return Array.newInstance(getRawType(componentType), 0).getClass();
            } else if (type instanceof TypeVariable) {
                return Object.class;
            } else if (type instanceof WildcardType) {
                return getRawType(((WildcardType) type).getUpperBounds()[0]);
            } else {
                String className = type == null ? "null" : type.getClass().getName();
                throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className);
            }
        }
    
    }
    //上面这个getRawType方法研究了很久,最后查看了Gson的源码发现了这段代码的写法,现分享给大家,希望有帮助。
  • 相关阅读:
    最不要勉强的,是感情.
    Nginx+phpfastcgi下flush 一下子全部输出问题
    php excel 读取日期问题
    JavaScript年月日和时间戳互转
    mysql 查找除id外其他重复的字段数据
    Thinkphp 下 MySQL group by 接count 获得条数方法
    MySQL性能管理及架构设计 --- 理论篇
    MySQL 导入.sql文件
    Apache ab 压力并发测试工具
    工作生活随笔
  • 原文地址:https://www.cnblogs.com/tiancai/p/9603050.html
Copyright © 2011-2022 走看看