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

注解的定义和使用

时间:2020-07-06 19:43:38      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:pre   int   void   epo   北京   retention   pack   tty   setname   

1 判断某个注解是否存在

判断某个注解是否存在于Class、Field、Method或Constructor:

Class.isAnnotationPresent(Class)
Field.isAnnotationPresent(Class)
Method.isAnnotationPresent(Class)
Constructor.isAnnotationPresent(Class)

例如:判断Person类是否存在注解@Report
Person.class.isAnnotationPresent(Report.class)

2 使用反射API读取注解

Class.getAnnotation(Class)
Field.getAnnotation(Class)
Method.getAnnotation(Class)
Constructor.getAnnotation(Class)

3 定义一个注解

/**
 * 定义一个注解,希望字符串的长度在0-255
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StringRange {
    int min() default 0;
    int max() default 255;
}

这个注解用在字段上,生命周期在运行期,默认的长度在0-255之间

4 定义一个Java实体类

package com.taobao;

public class Person {
    @StringRange(max=2)
    public String name;

    @StringRange(max=100)
    public String hobby;

    @StringRange
    public String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

5 检查是否符合注解要求

public class Check {
    public static void main(String[] args) throws IllegalAccessException {
        Person person = new Person();
        person.setAddress("中国北京");
        person.setHobby("怕啊啪啪");
        person.setName("nezha");
        check(person);

    }

    /**
     * 查看Person实例是否符合注解要求
     * @return
     */
    public static void  check(Person person) throws IllegalAccessException {
        Field[] fields = person.getClass().getFields();
        for (Field field : fields) {
            StringRange annotation = field.getAnnotation(StringRange.class);
            if (annotation!=null){
                int min = annotation.min();
                int max = annotation.max();
                // 通过反射拿到字段的值
                String str = (String)field.get(person);
                if (str.length()<min || str.length()>max){
                    throw new IllegalArgumentException(field.getName()+"参数范围错误");
                }

            }

        }
    }
}

可以通过反射拿到字段,拿到方法,拿到类,拿到构造器,然后再拿到注解,再拿到注解中的值,在应用在程序中。

注解的定义和使用

标签:pre   int   void   epo   北京   retention   pack   tty   setname   

原文地址:https://www.cnblogs.com/hellosiyu/p/13256273.html

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