Annotation类

来源:互联网 发布:自己的域名 编辑:程序博客网 时间:2024/06/05 07:13

package button2;
import java.lang.annotation.*;//未设置则表示所有范围
@Target(ElementType.CONSTRUCTOR)//annotation适用于构造方法,一般用枚举常量来设置适用范围
@Retention(RetentionPolicy.RUNTIME)//设置annotation的有效范围为最大(加载到AVM),叶童枚举常量
public @interface annotation1{
 String value()default"<默认构造方法>";
}

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

package button2;
import java.lang.annotation.*;
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER})//方法,成员变量,参数
@Retention(RetentionPolicy.RUNTIME)
public @interface annotation2 {
String describe();
@SuppressWarnings("rawtypes")
Class type()default void.class;//有默认值的Class成员
}

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

package button2;

public class Record {
@annotation2(describe="编号",type=int.class)
int id;
@annotation2(describe="姓名",type=String.class)
String name;
@annotation1
public Record() {}
 @annotation1("立即初始化构造方法")//构造方法的注释
 public Record(
   @annotation2(describe="编号",type=int.class)int id,
   @annotation2(describe="姓名",type=String.class)String name) {
  this.id=id;
  this.name=name;
  
 }
 @annotation2(describe="获得编号",type=int.class)//方法的注释
 public int getId() {
  return id;
 }
  @annotation2(describe="设置编号")
  public void setId(
    @annotation2(describe="编号",type=int.class)int id) {
   this.id=id;
  }
  @annotation2(describe="获得姓名",type=String.class)
  public String getName() {
   return name;
  }
  @annotation2(describe="设置姓名")
  public void setName(
    @annotation2(describe="姓名",type=String.class)String name) {
   this.name=name;
  }
 
}


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

package button2;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
public class getmain {
public static void main(String[]args) {
 Record record=new Record();
 @SuppressWarnings({ "rawtypes" })
 Class recordC=record.getClass();//获取record的信息
 @SuppressWarnings("rawtypes")
 Constructor[]declaredConstructors=recordC.getDeclaredConstructors();//获取构造方法信息
 for(int i=0;i<declaredConstructors.length;i++)
 {
  @SuppressWarnings("rawtypes")
  Constructor constructor=declaredConstructors[i];
  if(constructor.isAnnotationPresent(annotation1.class)) {//查看是否添加指定类型的注释
   @SuppressWarnings("unchecked")
   annotation1 ca=(annotation1)constructor.getAnnotation(annotation1.class);//将注释给ca
  System.out.println(ca.value()); 
  }
   Annotation[][]parameterAnnotations=constructor.getParameterAnnotations();//获得为所有参数添加的Annotation
  for(int j=0;j<parameterAnnotations.length;j++)
  {
   int length=parameterAnnotations[j].length;
   if(length==0)
    System.out.println("未添加Annotation参数");
   else
    for(int k=0;k<length;k++)
    {
     annotation2 pa=(annotation2)parameterAnnotations[j][k];
     System.out.println(""+pa.describe());
     System.out.println(""+pa.type());
    }
  }
  System.out.println();
 }
 
}
}