码迷,mamicode.com
首页 > 其他好文 > 详细

自定义注解

时间:2018-10-19 00:11:18      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:style   default   public   div   policy   use   end   如何   pen   

问题

如何通过注解值得到对应成员变量?

学习注解

自定义注解

@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Index {
    String name() default "";
}

定义User类

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class User {
    @Index(name = "userNo")
    private int userId;
    @Index(name = "Name")
    private String userName;
}

其中lombok的依赖配置为

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
</dependency>  

测试注解

public class UserTest {
    private void test1() {
        Class<User> clazz = User.class;
        Field[] fields = clazz.getDeclaredFields();
        List<Field> result = new ArrayList<>();
        for (Field field : fields){
            if(field.getAnnotation(Index.class)!=null) {
                result.add(field);
            }
        }

        for(Field list:result){
            System.out.println("被注解的字段为:" + list.getName());
        }
    }

    private void test2() {
        Class<User> clazz = User.class;
        Field[] fields = clazz.getDeclaredFields();
        List<String> result = new ArrayList<>();
        for (Field field : fields){
            if(field.getAnnotation(Index.class)!=null) {
                result.add(field.getAnnotation(Index.class).name());
            }
        }

        for(String list:result){
            System.out.println("注解的字段为:" + list);
        }
    }

    public static void main(String[] args) {
        UserTest userTest = new UserTest();
        userTest.test1();
        userTest.test2();
    }
}

结果

被注解的字段为:userId
被注解的字段为:userName
注解的字段为:userNo
注解的字段为:Name

解决

private void test3() {
        Map<String, String> annotation2Field = new HashMap<>();
        Class<User> clazz = User.class;
        
        
        
        Field[] fields = clazz.getDeclaredFields();
        List<String> result = new ArrayList<>();
        for (Field field : fields){
            if(field.getAnnotation(Index.class)!=null) {
                result.add(field.getAnnotation(Index.class).name());
                annotation2Field.put(field.getAnnotation(Index.class).name(), field.getName());
            }
        }
        annotation2Field.forEach((k, v)-> System.out.println(k + ":" + v));

    }

 

自定义注解

标签:style   default   public   div   policy   use   end   如何   pen   

原文地址:https://www.cnblogs.com/kaituorensheng/p/9813664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!