天天看點

java中自定義annotation

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

public @interface myannotation

{

}

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

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

 public string key() default "name";

 public string value() default "xy";

若要政策為運作時注解,需加上retention注解

@retention(value = retentionpolicy.runtime)

        public string value() default "xy";

三 為使annotation有意義,必須結合反射取得設定的内容,下面是一個完整的例子

myannotation.java

package cn.interfaces;

import java.lang.annotation.retention;

import java.lang.annotation.retentionpolicy;

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;

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和反射相結合會有很大的作用。