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

  • 相关阅读:
    微信端调取相册和摄像头,实现图片上传,并上传到本地服务器
    js 跳转链接的几种方式
    JS 导出表格
    This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed
    错误: 未能完成程序集的安装(hr = 0x8007000b)。探测终止。
    sql server ISNULL失效
    JS 实现加载中转圈效果
    .net core 分页控件X.PagedList.Mvc.Core
    JS 将table内未显示完全内容显示完全
    .net core viewbag 传递list 或 model
  • 原文地址:https://www.cnblogs.com/hunmeng/p/14159859.html
Copyright © 2011-2022 走看看