本文著重介紹怎么樣自定義Annotation以及使用自定義的Annotation。
ExtJS教程- Hibernate教程-Struts2 教程-Lucene教程
在Java Annotation(1)里,比較詳細(xì)地介紹了Annotation的作用,定義,JAVA標(biāo)準(zhǔn)Annotation等。本文著重介紹怎么樣自定義Annotation以及使用自定義的Annotation。
本文不對(duì)范例作詳細(xì)解釋,有不明白的地方請(qǐng)參考:Java Annotation(1) Annotation是一種特殊的interface。所以可以在annotation里定義方法,屬性;也可以讓某個(gè)類從annotation繼承(implements)。 下面從簡(jiǎn)單地范例開始,讓我們一步步加深對(duì)annotation的了解。 無任何方法/屬性Annotation范例:
MyAnnotation0.javapackage com.test.annotation;
MyAnnotation0為一個(gè)無任何方法和屬性的annotation。public @interface MyAnnotation0 { } 使用MyAnnotation0: TestMyAnnotation0.java @MyAnnotation0
public class TestMyAnnotation0 { @MyAnnotation0 public void testMethod() { } } 具有一個(gè)value方法Annotation范例:
MyAnnotation1.javapublic @interface MyAnnotation1 {
MyAnnotation1具有一個(gè)名為value的方法。/** * value method * @return value */ public String value(); } MyAnnotation1使用: TestMyAnnotation1.java @MyAnnotation1("hello")
可以通過@Annotation名(方法名1=值1, 方法名2=值2,
…)的形式給annotation賦值。只有一個(gè)方法的時(shí)候,可以直接省略為:@Annotation名(值1)
的賦值形式。當(dāng)方法返回一個(gè)數(shù)組時(shí),可以用 方法名={值1, 值2, …}給其賦值。public class TestMyAnnotation1 { @MyAnnotation1(value="world") public void testMethod() { } } 具有一個(gè)value方法和一個(gè)屬性Annotation范例:
如果必要,還可以在annotation里為其定義屬性。如下:MyAnnotation2.java @interface MyAnnotation2 {
其中,myProperty只能申明為public或無public修飾(無public修飾時(shí)也默認(rèn)為public)為static, final屬性(即使不寫也默認(rèn)為static, final)。public String value(); public String myProperty = "hello world"; } 使用例: TestMyAnnotation2 class TestMyAnnotation2 {
上例會(huì)打印出:public static void main(String[] args) { System.out.println(MyAnnotation2.myProperty); } @MyAnnotation2("") public void testMethod1() { } } hello world
復(fù)雜型annotation的定義與使用
本節(jié)介紹較為復(fù)雜的annotation定義與使用。先看代碼: MyAnnotation3.java public @interface MyAnnotation3 {
MyAnnotation3具有一個(gè)返回String的value方法,返回String[]的multiValues 方法;還有一個(gè)返回int 的number方法。其中number方法具有默認(rèn)值0。public String value(); public String[] multiValues(); int number() default 0; } 使用例: TestMyAnnotation3.java class TestMyAnnotation3 {
number具有默認(rèn)值,所以標(biāo)注時(shí)可以不為其賦值。其余方法則必須通過上面介紹的方法賦值。multiValues返回一個(gè)String[]數(shù)組,所以可以通過multiValues={"1", "2"}為其賦值。@MyAnnotation3(value = "call testMethod1", multiValues={"1", "2"}, number = 1) public void testMethod1() { } @MyAnnotation3(value = "call testMethod2", multiValues={"1", "2"}) public void testMethod2() { } } 本文對(duì)怎么自定義Annotation進(jìn)行了介紹,我們將在以后的文章里,著重介紹Annotation的應(yīng)用。 以上文章轉(zhuǎn)自:http://www.lifevv.com/
|
ExtJS教程- Hibernate教程-Struts2 教程-Lucene教程