java 注解使用

@参考博客1,@参考博客2

注解就相当于一个类,使用一个注解就相当于创建了注解类的一个实例对象

java内置注解,如

       @Deprecated 意思是“废弃的,过时的

       @Override 意思是“重写、覆盖

       @SuppressWarnings 意思是“压缩警告

注解(Annotation)相当于一种标记,javac编译器、开发工具等根据反射来了解你的类、方法、属性等元素是有具有标记,根据标记去做相应的事情。标记可以加在包、类、属性、方法、方法的参数及局部变量上。

 

注解就相当于一个你的源程序要调用一个类,在源程序中应用某个注解,得事先准备好这个注解类。就像你要调用某个类,得事先开发好这个类。

在一个注解类上使用另一个注解类,那么被使用的注解类就称为元注解。用来修饰自定义注解的Retention就是元注解,Retention有个RetentionPolicy类型的value();属性,有三种取值

如果一个注解中有一个名称为value的属性,且你只想设置value属性(即其他属性都采用默认值或者你只有一个value属性),那么可以省略掉“value=”部分。例如@SuppressWarnings("deprecation")

RetentionPolicy.SOURCE,只在java源文件中存在(.java),编译后不存在。如果做一些检查性的操作如 @Override 和 @SuppressWarnings,使用此注解

RetentionPolicy.CLASS,注解被保留到.class文件,,但jvm加载class文件时候被遗弃,这是默认的生命周期;(很遗憾,尽管看了很多博客我也没搞清这个)

RetentionPolicy.RUNTIME,注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解,比如@Deprecated使用RUNTIME注解

综合示例:

MyAnnotation注解:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE,ElementType.METHOD})//target注解决定MyAnnotation注解可以加到哪些成分上
@Retention(RetentionPolicy.RUNTIME)//Retention注解决定MyAnnotation注解的生命周期
public @interface MyAnnotation {
    String color() default "blue";//定义基本属性,并指定默认值
    String value();//定义一个名称为value的属性。value是特殊的基本属性
    int[] arr() default {1,2,3};//定义一个数组类型的属性
    ColorEnum clor() default ColorEnum.RED;//枚举类型的属性并指定默认值
    MetaAnnotation  authorName() default @MetaAnnotation("yanan");//MyAnnotation注解里使用MetaAnnotation注解,MetaAnnotation就被成为元注解
}
View Code

MetaAnnotation注解:

/**
 * TODO 做为元注解用
 * 2020年8月5日 
 * @author zhangyanan
 */
public @interface MetaAnnotation {
    String value();//设置特殊属性value
}
View Code

ColorEnum枚举:

/**
 * TODO 枚举类型的颜色
 * 2020年8月5日 
 * @author zhangyanan
 */
public enum ColorEnum {
    RED,BLUE,BLACK,YELLOW,WHITE,PINK
}
View Code

TestAnnotation测试类:

@MyAnnotation("zyn")//此处的zyn是对MyAnnotation特殊属性value的赋值
public class TestAnnotation {
    public static void main(String[] args) {
        //利用反射检查TestAnnotation类是否有注解
        if(TestAnnotation.class.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation annotation = TestAnnotation.class.getAnnotation(MyAnnotation.class);
            System.out.println(annotation.color());
            System.out.println(annotation.value());
            System.out.println(annotation.clor());
            System.out.println(annotation.arr()[2]);
            System.out.println(annotation.authorName().value());
        }else{
            System.out.println("TestAnnotation类没有MyAnnotation注解");
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/yanan7890/p/13435054.html