posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

元注解
@Target 表示注解可以用于哪些地方,CONSTRUCTOR:构造器,FIELD:字段(包括 enum 实例),LOCAL_VARIABLE:变量,METHOD:方法,PACKAGE:包,PARAMETER:参数,TYPE:类、接口(包括注解类型)或者 enum。
@Retention 表示注解信息保存的时长。SOURCE:注解将被编译器丢弃。CLASS:注解在 class 文件中可用,但是会被 VM 丢弃。 RUNTIME:VM 将在运行期也保留注解,可以通过反射机制读取注解。
@Documented 将此注解保存在 Javadoc 中
@Inherited 允许子类继承父类的注解
@Repeatable 允许一个注解可以被使用一次或者多次(Java 8)
注解示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.jay.SpringBootStudy8.annotation;
 
import java.lang.annotation.*;
 
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Documented
public @interface SelfDicCode {
    // 定义枚举
    public enum EnumType {
        none,
        project//项目
    }
    // 设置默认值
    public EnumType classType() default EnumType.none;
}

 注解处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Test
    public void testa() throws Exception {
        List<InboundMaster> list = new ArrayList<>();
        list.add(new InboundMaster("1", "1", "xxxxxx"));
 
        List<Project> projects = new ArrayList<>();
        projects.add(new Project("1", "项目1"));
 
        List<Field> fields = new ArrayList<>();//所有字段,包含父类
        Class<?> userClass = InboundMaster.class;
        fields.addAll(Arrays.asList(userClass.getDeclaredFields()));
//        while (userClass != null) {
//            fields.addAll(Arrays.asList(userClass.getDeclaredFields()));
//            userClass = userClass.getSuperclass();
//        }
        //循环字段,获取 SelfDicCode 注解
        for (Field field : fields) {
            SelfDicCode selfDicCode = field.getAnnotation(SelfDicCode.class);
            if (selfDicCode != null) {
                field.setAccessible(true);
                if (selfDicCode.classType() == SelfDicCode.EnumType.project) {
                    list.forEach(x -> {
                        try {
                            String o = field.get(x).toString();//projectId 1
                            Project first = projects.stream().filter(s -> s.getId().equals(o)).findFirst().get();
                            String name = first.getName();
                            x.getParams().put(field.getName(), name);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
        }
        list.forEach(System.out::println);
    }

  

posted on   邢帅杰  阅读(255)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示