java高薪之路__008_Annotation

时间:2021-06-23 11:11:08

元注解

共有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的子类
 package learn.JavaBasics.Class;

 import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@Documented
@Inherited
@interface myAnnotationDemo{
public String value() default "heollo annotation";
} @myAnnotationDemo(value="test class success")
public class TestAnnotation {
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
Class<?> clazz = TestAnnotation.class; if (clazz.isAnnotationPresent(myAnnotationDemo.class)) {
//获取类的注解
myAnnotationDemo mya = clazz.getAnnotation(myAnnotationDemo.class); System.out.println(mya.value()); //获取方法的注解
Method m = clazz.getMethod("testAnnotation");
myAnnotationDemo ma = m.getAnnotation(myAnnotationDemo.class); System.out.println(ma.value());
}
} @myAnnotationDemo(value="test method success")
public void testAnnotation(){ }
}