java高薪之路__008_Annotation

元注解

共有4种

@Retention 表示需要在什么级别保存该注释信息(生命周期)
  |--- RetentionPolicy.SOURCE: 停留在java源文件,编译器被丢掉
  |--- RetentionPolicy.CLASS: 停留在class文件中,但会被VM丢弃(默认)
  |--- RetentionPolicy.RUNTIME: 内存中的字节码,VM将在运行时也保留注解,因此可以通过反射机制读取注解的信息

@Target             默认值为任何元素,表示该注解用于什么地方
  |--- ElementType.CONSTRUCTOR:   构造器声明
  |--- ElementType.FIELD:       成员变量、对象、属性(包括enum实例)
  |--- ElementType.LOCAL_VARIABLE: 局部变量声明
  |--- ElementType.METHOD;      方法声明
  |--- ElementType.PACKAGE:     包声明
  |--- ElementType.PARAMETER:    参数声明
  |--- ElementType.TYPE:       类、接口(包括注解类型)或enum声明

@Documented    将注解包含在JavaDoc中,Documented是一个标记注解,没有成员

@Inheried    允许子类继承父类中的注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类
 1 package learn.JavaBasics.Class;
 2 
 3 import java.lang.annotation.Documented;
 4 import java.lang.annotation.ElementType;
 5 import java.lang.annotation.Inherited;
 6 import java.lang.annotation.Retention;
 7 import java.lang.annotation.RetentionPolicy;
 8 import java.lang.annotation.Target;
 9 import java.lang.reflect.Method;
10 
11 @Retention(RetentionPolicy.RUNTIME)
12 @Target({ElementType.TYPE,ElementType.METHOD})
13 @Documented
14 @Inherited
15 @interface myAnnotationDemo{
16     public String value() default "heollo annotation";
17 }
18 
19 @myAnnotationDemo(value="test class success")
20 public class TestAnnotation {
21     public static void main(String[] args) throws SecurityException, NoSuchMethodException {
22         Class<?> clazz = TestAnnotation.class;
23         
24         if (clazz.isAnnotationPresent(myAnnotationDemo.class)) {
25             //获取类的注解
26             myAnnotationDemo mya = clazz.getAnnotation(myAnnotationDemo.class);
27             
28             System.out.println(mya.value());
29             
30             //获取方法的注解
31             Method m = clazz.getMethod("testAnnotation");
32             myAnnotationDemo ma = m.getAnnotation(myAnnotationDemo.class);
33             
34             System.out.println(ma.value());
35         }
36     }
37     
38     @myAnnotationDemo(value="test method success")
39     public void testAnnotation(){
40         
41     }
42 }
View Code
原文地址:https://www.cnblogs.com/hangtt/p/4855202.html