天天看点

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