注解的使用非常簡單,只需在需要注解的地方標明某個注解即可,例如在方法上注解:
1
2
3
4
5
6
|
public class Test { @Override public String tostring() { return "override it" ; } } |
例如在類上注解:
1
2
3
|
@Deprecated public class Test { } |
所以Java內置的注解直接使用即可,但很多時候我們需要自己定義一些注解,例如常見的spring就用了大量的注解來管理對象之間的依賴關系。下面看看如何定義一個自己的注解,下面實現這樣一個注解:通過@Test向某類注入一個字符串,通過@TestMethod向某個方法注入一個字符串。
1.創建Test注解,聲明作用于類并保留到運行時,默認值為default。
1
2
3
4
5
|
@Target ({ElementType.TYPE}) @Retention (RetentionPolicy.RUNTIME) public @interface Test { String value() default "default" ; } |
2.創建TestMethod注解,聲明作用于方法并保留到運行時。
1
2
3
4
5
|
@Target ({ElementType.METHOD}) @Retention (RetentionPolicy.RUNTIME) public @interface TestMethod { String value(); } |
3.測試類,運行后輸出default和tomcat-method兩個字符串,因為@Test沒有傳入值,所以輸出了默認值,而@TestMethod則輸出了注入的字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Test () public class AnnotationTest { @TestMethod ( "tomcat-method" ) public void test(){ } public static void main(String[] args){ Test t = AnnotationTest. class .getAnnotation(Test. class ); System.out.println(t.value()); TestMethod tm = null ; try { tm = AnnotationTest. class .getDeclaredMethod( "test" , null ).getAnnotation(TestMethod. class ); } catch (Exception e) { e.printStackTrace(); } System.out.println(tm.value()); } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/wangyangzhizhou/article/details/51576460