自定义注解

它类似于新创建一个接口文件,但为了区分,我们需要将它声明为@interface,如下例:

public @interface NewAnnotation {

}

使用自定义的注解类型

 

public class AnnotationTest {

    @NewAnnotation

    public static void main(String[]args) {

    }

}

为自定义注解添加变量

public @interface NewAnnotation {

    String value();

}

 

public class AnnotationTest {

    @NewAnnotation("mainmethod")

    public static void main(String[]args) {

        saying();

    }    

    @NewAnnotation(value="saymethod")

    public static void saying() {

    }

}

定义一个枚举类型,然后将参数设置为该枚举类型,并赋予默认值

   public @interface Greeting {

    public enum FontColor {

        BLUE,

        RED,

        GREEN

    };

    String name();

    FontColor fontColor() default FontColor.RED;

}

这里有两种选择,其实变数也就是在赋予默认值的参数上,我们可以选择使用该默认值,也可以重新设置一个值来替换默认值

public class AnnotationTest {

    @NewAnnotation("mainmethod")

    public static void main(String[]args) {

        saying();

        sayHelloWithDefaultFontColor();

        sayHelloWithRedFontColor();

    } 

    @NewAnnotation("saymethod")

    public static void saying() {

    }    

    // 此时的fontColor为默认的RED

    @Greeting(name="defaultfontcolor")

    public static void sayHelloWithDefaultFontColor() {

    }

    // 将fontColor改为BLUE

    @Greeting(name="notdefault", fontColor=Greeting.FontColor.BLUE)

    public static void sayHelloWithRedFontColor() {

    }

}

 
原文地址:https://www.cnblogs.com/loaderman/p/6407599.html