閱讀970 返回首頁    go 阿裏雲 go 技術社區[雲棲]


java中自定義annotation


一 自定義注解的語法很簡單

public @interface MyAnnotation
{

}

上麵的代碼就定義了一個空注解,名字為MyAnnotation。

 

 


二 自定義注解也可以有屬性

public @interface MyAnnotation
{
 public String key() default "name";
 public String value() default "xy";
}

若要策略為運行時注解,需加上Retention注解

@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
 public String key() default "name";
        public String value() default "xy";
}

 


三 為使Annotation有意義,必須結合反射取得設置的內容,下麵是一個完整的例子


MyAnnotation.java
package cn.interfaces;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
 public String key() default "name";
 public String value() default "xy";
}

 

SimpleBean.java
package cn.bean;
import cn.interfaces.MyAnnotation;

public class SimpleBean
{
 @MyAnnotation(key = "name", value = "xy")
 public void save()
 {
  System.out.println("save");
 }
}

 

Test.java
package cn.test;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import cn.interfaces.MyAnnotation;

public class Test
{
 public static void main(String[] args) throws IOException,
                                ClassNotFoundException, SecurityException, NoSuchMethodException
 {
  Class<?> c = Class.forName("cn.bean.SimpleBean");
  Method saveMethod = c.getMethod("save");
  Annotation an[] = saveMethod.getAnnotations(); // 取得全部的運行時Annotation
  for (Annotation a : an)
  {
   System.out.println(a);
  }

  if (saveMethod.isAnnotationPresent(MyAnnotation.class)) // 該方法上是否存在該種類型的注解
  {
   MyAnnotation ma = saveMethod.getAnnotation(MyAnnotation.class);
   String key = ma.key();
   String value = ma.value();
   System.out.println("key = " + key);
   System.out.println("value = " + value);
  }
 }
}

 

輸出結果

@cn.interfaces.MyAnnotation(value=xy, key=name)
key = name
value = xy

 


結論

annotation和反射相結合會有很大的作用。

 

 

最後更新:2017-04-03 16:49:28

  上一篇:go jQuery中的$.extend方法來擴展JSON對象
  下一篇:go oracle中兩表之間值互相插入和表自身插入值