使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。
自定义最简单的注解:
public @interface MyAnnotation { }
使用自定义注解:
public class AnnotationTest2 { @MyAnnotation public void execute(){ System.out.println("method"); } }
5.1、添加变量:
public @interface MyAnnotation { String value1(); }
使用自定义注解:
public class AnnotationTest2 { @MyAnnotation(value1="abc") public void execute(){ System.out.println("method"); } }
当注解中使用的属性名为value时,对其赋值时可以不指定属性的名称而直接写上属性值接口;除了value意外的变量名都需要使用name=value的方式赋值。
5.2、添加默认值:
public @interface MyAnnotation { String value1() default "abc"; }
5.3、多变量使用枚举:
public @interface MyAnnotation { String value1() default "abc"; MyEnum value2() default MyEnum.Sunny; } enum MyEnum{ Sunny,Rainy }
使用自定义注解:
public class AnnotationTest2 { @MyAnnotation(value1="a", value2=MyEnum.Sunny) public void execute(){ System.out.println("method"); } }
5.4、数组变量:
public @interface MyAnnotation { String[] value1() default "abc"; }
使用自定义注解:
public class AnnotationTest2 { @MyAnnotation(value1={"a","b"}) public void execute(){ System.out.println("method"); } }