← 返回首页
JavaSE系列教程(八十七)
发表时间:2020-02-29 21:46:06
讲解自定义注解。

1.自定义注解语法

[public] @interface Annotation的名称
{
  [数据类型 变量名称();]
}

2.自定义注解使用的元注解

所谓元注解就是使用在自定义注解上的注解,常用的原注解有以下:@Target,@Retention,@Document,@Inherited等注解。

@Target 表明该注解可以应用的java元素类型。

@Retention 表明该注解的生命周期

@Document 表明该注解标记的元素可以被Javadoc 或类似的工具文档化

@Inherited 表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解

3.自定义注解实例

实例:自定义MyAnnotation注解如下。

@Documented
@Target(value={ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

public @interface MyAnnotation {

    String value() default "";
}

设计TestMyAnnotation测试类,在setName(String name)方式上添加@MyAnnotation注解,实现功能如下: 调用setName(String name) 方法时判断该方法上是否有@MyAnnotation注解,如果有,属性name赋值为注解的value属性值,否则属性name赋值为参数name的值.

测试代码如下:

public class TestMyAnnotation {

    private String name; //null

    private void fn(String args) {

    }

    public String getName() {
        return name;
    }


    @MyAnnotation(value="张三丰")
    public void setName(String name) {
        try {

            Class clazz = this.getClass();
            Method method = clazz.getDeclaredMethod("setName", String.class);
            //获取方法上的所有注解。
            Annotation[] annotations = method.getAnnotations();
            MyAnnotation currentAnnotation=null;

            boolean flag = false;
            for (Annotation anno : annotations) {
                //判断是否存在MyAnnotation注解。
                if (anno.annotationType() == MyAnnotation.class) {
                    currentAnnotation = (MyAnnotation) anno;
                    flag = true;
                    break;
                }
            }

            if(flag){
                //如果存在MyAnnotation注解,this.name属性赋值为注解的value属性。
                String value = currentAnnotation.value();
                this.name = value;
            }else{
                this.name = name;//否则this.name赋值为参数name值。
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public static void main(String[] args) {

        TestMyAnnotation t = new TestMyAnnotation();
        t.setName("张三");
        System.out.println(t.name);
    }
}

运行结果:
张三丰

如果setName方法上未添加@MyAnnotation注解,上例的运行结果如下:

运行结果:
张三

4.自定义注解的使用场合

有很多第三方注解比如:Spring,Mybatis等,其内部也是通过自定义注解方式实现的。因此自定义注解广泛应用于各类javaee框架中,实现诸如:权限认证、日志管理、事务等功能。