Anotación constante personalizada @Desc

package com.zyq.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 通用配置注解
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Desc {

    String value();

    String remark() default "";

}
package com.zyq.util;

import java.lang.reflect.Field;
import java.util.*;

import com.zyq.annotation.Desc;
import com.zyq.entity.vo.DescAttr;

/**
 * 常量注解工具类
 * 
 * @author ZhangYuanqiang
 * @since 2021年4月14日
 */
public class DescUtil {

    /**
     * 获取打了Desc注解类的字典属性列表
     * 
     * @param cls_指定类
     * @return 字典属性列表
     */
    public static <T> List<DescAttr> getAttrList(Class<T> cls) {
        try {
            Field[] fields = cls.getDeclaredFields();
            List<DescAttr> attrList = new LinkedList<>();
            for (Field field : fields) {
                Desc desc = field.getAnnotation(Desc.class);
                if (desc != null) {
                    DescAttr vo = new DescAttr();
                    vo.setKey(field.getInt(cls));
                    vo.setValue(desc.value());
                    vo.setRemark(desc.remark());
                    attrList.add(vo);
                }
            }
            return attrList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

    /**
     * 获取某个属性值的Desc注解
     *
     * @param cls_类
     * @param key_属性值
     * @return 注解
     */
    private static <T> Desc getDesc(Class<T> cls, int key) {
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            int i = 0;
            try {
                i = field.getInt(cls);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (i == key) {
                return field.getAnnotation(Desc.class);
            }
        }
        return null;
    }

    /**
     * 获取某个属性值的Desc注解的Value值
     *
     * @param cls_类
     * @param key_属性值
     * @return 注解
     */
    public static <T> String getValue(Class<T> cls, int key) {
        Desc desc = DescUtil.getDesc(cls, key);
        if (desc != null) {
            return desc.value();
        }
        return "";
    }

    public static <T> boolean isContainKey(Class<T> cls, int key) {
        return !Objects.isNull(DescUtil.getDesc(cls, key));
    }

}
package com.zyq.entity.vo;

import lombok.Data;

/**
 * Desc 注解解析后的实体
 * 
 * @author ZhangYuanqiang
 * @since 2021年4月14日
 */
@Data
public class DescAttr {

    public int key;
    public String value;
    public String remark;

}

Supongo que te gusta

Origin blog.csdn.net/sunnyzyq/article/details/118206827
Recomendado
Clasificación