- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.TYPE)
- public @interface MyAnnotation {
- String value() default "myannotation.value";
- }
复制代码
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import com.synaric.enumeration.*;
- //表明该注解保留到内存(运行时)
- @Retention(RetentionPolicy.RUNTIME)
- //表明该注解可以运用到Type中
- //Type包括Class、Interface、Enum
- @Target(ElementType.TYPE)
- public @interface InfoAnnotation {
- //包含各种各样类型的注解
- String message() default "my info";
-
- int cid() default 0;
-
- int[] arr() default {1, 2, 3};
-
- Color color() default Color.BLACK;
-
- MyAnnotation annotation() default @MyAnnotation();
-
- Class<?> myclass() default AnnotataionDemo_2.class;
-
- String value();
- }
复制代码
- import java.util.Arrays;
- //@InfoAnnotation("my value") ok
- //@InfoAnnotation(message="my message",value="my value") ok
- //有默认值的属性可以不设置值
- //如果只需要设置value属性,不需要写成@InfoAnnotation(value="my value")
- @InfoAnnotation("my value")
- public class AnnotataionDemo_2 {
- public static void main(String[] args) {
- //检查该类是否运用了注解
- if(AnnotataionDemo_2.class.isAnnotationPresent(InfoAnnotation.class)){
- //反射获取注解
- InfoAnnotation infoAnnotation = AnnotataionDemo_2.class.getAnnotation(InfoAnnotation.class);
-
- //打印各种类型注解
- System.out.println(infoAnnotation.message());
- System.out.println(infoAnnotation.cid());
- System.out.println(Arrays.toString(infoAnnotation.arr()));
- System.out.println(infoAnnotation.color());
- System.out.println(infoAnnotation.annotation());
- System.out.println(infoAnnotation.myclass());
- System.out.println(infoAnnotation.value());
- }
- }
- }
复制代码
|
|