Java注解详解

注解相当于一个特殊的类。
定义一个简单的注解并使用,细节在注释中:

MyFirstAnnotation.java

/**
 * java在编译的过程中可能会把一些注解文件丢掉,使用
 * @Retention(RetentionPolicy.RUNTIME)注解让该注解一直保存到运行阶段
 * @Retention(RetentionPolicy.CLASS),保存到编译阶段,默认即此
 * @Retention(RetentionPolicy.SOURCE)保存到源文件阶段
 *
 *@Target({ElementType.METHOD,ElementType.TYPE})表示
 *该注解可以在类上,也可以在方法上
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyFirstAnnotation {

}

AnnotationTest.java

@MyFirstAnnotation
public class AnnotationTest {

    @Test
    public void test3(){
        if (AnnotationTest.class.isAnnotationPresent(MyFirstAnnotation.class)) {
            MyFirstAnnotation mfa = AnnotationTest.class
                    .getAnnotation(MyFirstAnnotation.class);
            System.out.println(mfa);
        }
    }
}

输出:

@lenve.test.MyFirstAnnotation()

为注解增加一个方法,并且调用该方法:
MyFirstAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyFirstAnnotation {

    //公共的抽象的方法返回一个字符串,前面的东西省略
    String color();
}
@MyFirstAnnotation(color="red")
public class AnnotationTest {

    @Test
    public void test3(){
        if (AnnotationTest.class.isAnnotationPresent(MyFirstAnnotation.class)) {
            MyFirstAnnotation mfa = AnnotationTest.class
                    .getAnnotation(MyFirstAnnotation.class);
            System.out.println(mfa.color());
        }
    }
}

输出:

red

注解返回枚举类型和注解类型:
MyFirstAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyFirstAnnotation {

    //公共的抽象的方法返回一个字符串,前面的东西省略
    String color() default "blue";
    String value();
    int[] arrayAttr() default {1,2,3};
    MyColorEnum retEnum() default MyColorEnum.BLUE;
    MySecondAnnotation retAnnotation() default @MySecondAnnotation("zhangsan");
}

MyColorEnum.java

public enum MyColorEnum {
        RED,BLUE,GREEN,YELLO,GRAY;
}

MySecondAnnotation.java

public @interface MySecondAnnotation {
    String value();
}

AnnotationTest.java

@MyFirstAnnotation(retAnnotation=@MySecondAnnotation("lisi"),color = "red", value = "abc", arrayAttr = { 4, 5, 6 }, retEnum = MyColorEnum.RED)
public class AnnotationTest {

    @Test
    // 如果方法名为value可以省略
    @MyFirstAnnotation("xyz")
    public void test3() {
        if (AnnotationTest.class.isAnnotationPresent(MyFirstAnnotation.class)) {
            MyFirstAnnotation mfa = AnnotationTest.class
                    .getAnnotation(MyFirstAnnotation.class);
            System.out.println(mfa.color() + "," + mfa.value());
            System.out.println(mfa.retEnum());
            System.out.println(mfa.retAnnotation().value());
        }
    }
}
原文地址:https://www.cnblogs.com/lenve/p/4518004.html