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

  • 相关阅读:
    kube-apiserver
    深度学习三:卷积神经网络
    深度学习二:概率和反向传播的变种
    深度学习一:深度前馈网络和反向传播
    Knowledge 1:Propositional Logic 命题逻辑基础及符号
    评估方法:留出法、交叉验证法、自助法、调参与最终模型
    你曾这样问过
    套路总结
    NOI2020游记
    curl不是内部或外部命令,也不是可运行的程序或批处理文件
  • 原文地址:https://www.cnblogs.com/hunmeng/p/14159859.html
Copyright © 2011-2022 走看看