0
点赞
收藏
分享

微信扫一扫

Java 通过反射获取注解值


package com.zyq.consts;

import com.zyq.annotation.Desc;

/**

 * 用户状态

 * @author zyq

 * @date 2019-04-22

 */

public class UserStatus {

    @Desc(value = "正常")

![](https://s2.51cto.com/images/20220812/1660315859559025.jpg)

    public static int NORMAL = 1;

    @Desc(value = "非正常", remark="该状态用户不能登录")

    public static int ABNORMAL = 2;

}

(3)定义一个与注解属性对应的类


package com.zyq.vo;

public class FixedVo {

    public int key;

    public String value;

    public String remark;

    public int getKey() {

        return key;

    }

    public String getValue() {

        return value;

    }

    public String getRemark() {

        return remark;

    }

    public void setKey(int key) {

        this.key = key;

    }

    public void setValue(String value) {

        this.value = value;

    }

    public void setRemark(String remark) {

        this.remark = remark;

    }

    @Override

    public String toString() {

        return "FixedVo [key=" + key + ", value=" + value + ", remark="

                + remark + "]";

    }

}

(4)创建一个注解工具类,提供解析注解的方法


package com.zyq.tools;

import java.lang.reflect.Field;

import java.util.Collections;

import java.util.LinkedList;

import java.util.List;

import com.zyq.annotation.Desc;

import com.zyq.vo.FixedVo;

public class AnnotationTool {

    /**

     * 获取打了Desc注解的字典属性列表

     * @param t 类

     * @return 字典属性列表

     */

    public static <T> List<FixedVo> getFixedVoList(Class<T> c) {

        if (c == null) {

            return Collections.emptyList();

        }

        try {

            T cls = c.newInstance();

            Field[] fields = c.getDeclaredFields();

            List<FixedVo> fixedVoList = new LinkedList<FixedVo>();

            for (Field field : fields) {

                Desc desc = field.getAnnotation(Desc.class);

                if (desc != null) {

                    FixedVo vo = new FixedVo();

                    vo.setKey(field.getInt(cls));

                    vo.setValue(desc.value());

                    vo.setRemark(desc.remark());

                    fixedVoList.add(vo);

                }

            }

            return fixedVoList;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return Collections.emptyList();

    }

}

(4)测试类代码


package com.zyq.tools.test;

import java.util.List;

import org.junit.Test;

import com.zyq.consts.UserStatus;

import com.zyq.tools.AnnotationTool;

import com.zyq.vo.FixedVo;

public class AnnotationToolTest {

    @Test

    public void getFixedVoListTest(){

        List<FixedVo> voList = AnnotationTool.getFixedVoList(UserStatus.class);

        for (FixedVo vo : voList) {

            System.out.println(vo.toString());

        }

    }

}

(4)测试结果:


FixedVo [key=1, value=正常, remark=]

FixedVo [key=2, value=非正常, remark=该状态用户不能登录]

[

举报

相关推荐

0 条评论