首页 > 其他分享 >ReflectUtils

ReflectUtils

时间:2022-08-23 10:45:21浏览次数:41  
标签:key list tittleList field result ReflectUtils import

package com.denkou.project.service.zxzy.utils;

import com.denkou.project.service.zxzy.exception.ApiException;
import io.swagger.annotations.ApiModelProperty;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Create By denkou
 * 特定处理通用反射类
 *
 * @Date 8/4/2022 7:59 PM
 */
@Slf4j
public class ReflectUtils {

    /**
     * 
     * @param k  实体类
     * @param p  实体类对应数据
     * @param result  返回组合
     */
    @SneakyThrows
    public static void getValues(Object k, Object p, Map<String, List<Object>> result) {
        Field[] fields = k.getClass().getDeclaredFields();//包括公共、受保护、默认(包)访问和私有字段,但不包括继承的字段
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getName().equals("serialVersionUID") || field.getName().equals("platformId")) {
                continue;
            }
            try {
                String key = field.getName();
                Object value = field.get(p);
                //不同场合对list进行不同的操作
                List<Object> list;
                if (result.containsKey(key)) {
                    list = result.get(key);
                } else {
                    list = new ArrayList<>();
                }
                if (!list.contains(value)) {
                    list.add(value);
                }
                result.put(key, list);

                if (field.isAnnotationPresent(ApiModelProperty.class)) {
                    ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                    String keyName = key + "name";
                    String chinesName = annotation.value();

                    //不同场合对list进行不同的操作
                    List<Object> tittleList;
                    if (result.containsKey(keyName)) {
                        tittleList = result.get(keyName);
                    } else {
                        tittleList = new ArrayList<>();
                    }
                    if (!tittleList.contains(chinesName)) {
                        tittleList.add(chinesName);
                    }
                    result.put(keyName, tittleList);
                }
            } catch (IllegalArgumentException e) {
                throw new ApiException("发生未知异常");
            } catch (IllegalAccessException e) {
                throw new ApiException("发生未知异常");
            }
        }
    }
}

 

标签:key,list,tittleList,field,result,ReflectUtils,import
From: https://www.cnblogs.com/denkou/p/16615189.html

相关文章