关于注解的使用和编写及解释

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;
@Inherited
@Documented
@Retention (RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})
public @interface MyAnno2 {
public String schoolName() default "a";

}

/////////////////////////////////////////////////////


为注解添加成员 

//定义

public @interface MyAnno {
  public String schoolName();
}

//使用
@MyAnno(schoolName="湖南城市学院")
public class UserModel{

指定目标 Target

在了解如何使用Target 之前,需要认识另一个类,该类被称为ElementType (通过API详细学习) ,它实际上是一个枚举。这个枚举定义了注释类型可应用的不同程序元素。 @Target({ ElementType.TYPE, ElementType.METHOD})

设置保持性 Retention

 RetentionPolicy (通过API详细学习)枚举类中定义了3种注解保持性,分别决定了Java 编译器以何种方式处理注解。  @Retention(RetentionPolicy.SOURCE) 

设置继承 Inherited 

在默认的情况下,父类的注解并不会被子类继承。如果要继承,就必须加上Inherited注解。 @Inherited 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

如何读取注解

import java.lang.reflect.*;
public class TestMyAnno {
  public static void main(String[] args)throws Exception {
    Class c = Class.forName(“anno.UserModel");
    boolean flag = c.isAnnotationPresent(MyAnno.class);
    System.out.println(flag);
    if(flag){
      MyAnno ma = (MyAnno)c.getAnnotation(MyAnno.class);
      System.out.println("学校名称:=="+ma.schoolName());
      //获取到了这些数据过后,下面就可以开始你的处理了
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_35307947/article/details/80430079