pojo转换接口说明方法

2 篇文章 0 订阅

pojo转换接口说明方法

package com.yonyou.convert.service;

import com.alibaba.fastjson.JSON;
import com.yonyou.convert.dto.ResponseDto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Size;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Description: pojo转换接口说明方法
 * @ClassName: ConvertService
 * @Author zhaomxr
 * @Date 2021-08-10 09:47
 */
@Slf4j
@Service
public class ConvertService {

    /**
     * 执行转换
     * 返回当前bean的实体对象
     *
     * @param aClass   class类
     * @param fieldMap 排除的字段
     */
    public Object executeToObject(Class<?> aClass, Map fieldMap) throws IllegalAccessException, InstantiationException {
        //1.取所有field属性字段
        Field[] declaredFields = aClass.getDeclaredFields();
        Object instance = aClass.newInstance();

        Arrays.stream(declaredFields).forEach(field -> {
            field.setAccessible(true);
            //2.过滤排除字段
            if (!fieldMap.containsKey(field)) {
                ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                boolean annotationPresent = field.isAnnotationPresent(ApiModelProperty.class);
                Object value = !annotationPresent || annotation.value() == null || StringUtils.isBlank(annotation.value()) ? "" : annotation.value();
                try {
                    field.set(instance, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

        log.info("", JSON.toJSONString(instance));
        return instance;
    }

    /**
     * 执行转换
     * 返回标准JSON字符串
     *
     * @param aClass
     * @param fieldMap
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public String executeToJsonStringByApiModelProperty(Class<?> aClass, Map fieldMap) throws IllegalAccessException, InstantiationException {
        //1.取所有field属性字段
        Field[] declaredFields = aClass.getDeclaredFields();
        Map<String, Object> classMap = new HashMap<>(32);

        Arrays.stream(declaredFields).forEach(field -> {
            field.setAccessible(true);
            //2.过滤排除字段
            if (!fieldMap.containsKey(field)) {
                //3.判断是否存在指定注解
                ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                boolean annotationPresent = field.isAnnotationPresent(ApiModelProperty.class);
                Object value = !annotationPresent || annotation.value() == null || StringUtils.isBlank(annotation.value()) ? "" : annotation.value();
                //4.key为field名称,value为注解中说明值
                classMap.put(field.getName(), value);
            }
        });

        log.info("标准JSON结果:{}", JSON.toJSONString(classMap));
        return JSON.toJSONString(classMap);
    }

    /**
     * 多个实体dto返回list
     *
     * @param classPaths
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws ClassNotFoundException
     */
    public Object executeToJsonStringByApiModelProperty(String typeBoolean, String sizeBoolean, String url, String type, String explain, String... classPaths) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        List resultList = new ArrayList<>();
        Arrays.stream(classPaths).forEach(classPath -> {
            try {
                ResponseDto responseDto = executeToJsonStringByApiModelProperty(typeBoolean, sizeBoolean, classPath, new HashMap<>(16));
                responseDto.setUrl(url);
                responseDto.setType(type);
                responseDto.setExplain(explain);
                resultList.add(responseDto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return resultList;
    }

    /**
     * 执行转换
     * 返回标准JSON字符串
     *
     * @param classPath
     * @param fieldMap
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public ResponseDto executeToJsonStringByApiModelProperty(String typeBoolean, String sizeBoolean, String classPath, Map fieldMap) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        //反射获取类的class
        Class<?> aClass = Class.forName(classPath);
        //1.取所有field属性字段
        Field[] declaredFields = aClass.getDeclaredFields();
        Map<String, Object> classMap = new HashMap<>(32);

        Arrays.stream(declaredFields).forEach(field -> {
            field.setAccessible(true);
            //2.过滤排除字段
            if (!fieldMap.containsKey(field)) {
                //3.构建字段对应说明,key为field名称,value为注解中说明值
                classMap.put(field.getName(), buildValue(typeBoolean, sizeBoolean, field));
            }
        });

        String beanDesc = "";
        if (aClass.isAnnotationPresent(ApiModel.class)) {
            ApiModel annotation = aClass.getAnnotation(ApiModel.class);
            beanDesc = (annotation == null || StringUtils.isBlank(annotation.description()) ? "" : annotation.description());
        }

        log.info("标准JSON结果:{}", JSON.toJSONString(classMap));
        return new ResponseDto(beanDesc, classPath, classMap);
    }

    /**
     * 构建字段对应说明
     *
     * @param field
     * @return
     */
    private String buildValue(String typeBoolean, String sizeBoolean, Field field) {
        StringBuilder stringBuilder = new StringBuilder();

        //判断是否存在指定注解
        ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
        boolean annotationPresent = field.isAnnotationPresent(ApiModelProperty.class);
        //desc
        Object value = !annotationPresent || annotation.value() == null || StringUtils.isBlank(annotation.value()) ? "" : annotation.value();
        if (value != null && !StringUtils.isBlank(value.toString())) {
            stringBuilder.append("【");
            stringBuilder.append("desc:" + value.toString());
            stringBuilder.append("】");
        }

        //type
        if (Objects.equals(typeBoolean, "1")) {
            int lastIndexOf = field.getType().getName().lastIndexOf(".");
            String type = field.getType().getName().substring(lastIndexOf + 1);
            if (!StringUtils.isBlank(type)) {
                stringBuilder.append("【");
                stringBuilder.append("type:" + type);
                stringBuilder.append("】");
            }
        }

        //size
        if (Objects.equals(sizeBoolean, "1")) {
            Size size = field.getAnnotation(Size.class);
            String sizeStr = size == null ? "" : "" + size.max();
            if (!StringUtils.isBlank(sizeStr)) {
                stringBuilder.append("【");
                stringBuilder.append("max-size:" + sizeStr);
                stringBuilder.append("】");
            }
        }

        return stringBuilder.toString();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值