反射获取List中的泛型

获取List中的泛型类型,创建对象,并且字段设置值

for (Field f : partPropType.getDeclaredFields()) {
            if ("accountPrincipalApproveList".equals(f.getName())) {
                f.setAccessible(true);
                List accountPrincipalApproveList = new ArrayList();
                if(f.getType() == java.util.List.class){
                    // 如果是List类型,得到其Generic的类型
                    Type genericType = f.getGenericType();
                    if(genericType == null) continue;
                    // 如果是泛型参数的类型
                    if(genericType instanceof ParameterizedType){
                        ParameterizedType pt = (ParameterizedType) genericType;
                        //得到泛型里的class类型对象
                        Class<?> accountPrincipalApproveClazz = (Class<?>)pt.getActualTypeArguments()[0];
                        Object accountPrincipalApprove = accountPrincipalApproveClazz.newInstance();
                        PropertyDescriptor acctApproveIdPropertyDescriptor = new PropertyDescriptor("acctApproveId", accountPrincipalApproveClazz);
                        acctApproveIdPropertyDescriptor.getWriteMethod().invoke(inputPartObject, "ACCOUNT_TYPE_NONE");
                        accountPrincipalApproveList.add(accountPrincipalApprove);
                    }
                }
                f.set(inputPartObject,accountPrincipalApproveList);
                break;
            }
        }

猜你喜欢

转载自gwj41.iteye.com/blog/2382631