Java 反射获取对象属性中泛型类属性信息

例: class xxxx {

private List persons;

}

获取 Person 中的field等等

具体代码:

Field[] declaredFields = xxxx.class.getDeclaredFields();
for (Field declaredField : declaredFields) {
        declaredField.setAccessible(true);
        //主要代码
        Type genericType = declaredField.getGenericType();
        if(genericType instanceof ParameterizedType){
            ParameterizedType type = (ParameterizedType) genericType;
            Type[] actualTypeArguments = type.getActualTypeArguments();
            if(actualTypeArguments.length > 0){
                Class clazz = (Class) actualTypeArguments[0];
                List collect = Arrays.stream(clazz.getDeclaredFields())
                        .map(field -> field.getName())
                        .collect(Collectors.toList());
            }
        }
    }

}

你可能感兴趣的:(JAVA,java)