zoukankan      html  css  js  c++  java
  • 泛型实例化,参数实例化

        /**
         * 初始化
         * @param parameter 参数
         * @return 实例化的对象
         */
        protected H init(String parameter){
            Type superClass = getClass().getGenericSuperclass();
          //获取第二个枚举对象 Type type
    = ((ParameterizedType) superClass).getActualTypeArguments()[1]; Class<?> clazz = getRawType(type); try {
            //获取构造函数列表
    final Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
            //获取构造函数参数,定义实例化对象的参数类型
    final Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(declaredConstructors[0].getParameterTypes()); declaredConstructor.setAccessible(true); return (H) declaredConstructor.newInstance(parameter, "qeqweqwew"); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new ServiceException(e.getMessage(),e.getCause()); } }

        /**
         * type不能直接实例化对象,通过type获取class的类型,然后实例化对象
         * @param type 类型
         * @return 对象
         */
        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);
            }
        }

    https://www.cnblogs.com/tiancai/p/9603050.html
    https://www.cnblogs.com/duanweishi/p/4480163.html

  • 相关阅读:
    IOS开发 网络发展史(NSURLProtocol)
    IOS开发 网络发展史(NSURLCach)
    IOS 开发 网络发展史(URLConnection)
    ios 网络开发(CFNetwork)
    MAC安装mysql
    conda 安装常用包
    从必应上拉取图片
    旋转数组中的二分查找
    东北大学 python模拟登录校园网(2019年6月启用新登录模式后)
    Ubuntu 安装Codeblocks
  • 原文地址:https://www.cnblogs.com/hunmeng/p/14159859.html
Copyright © 2011-2022 走看看