Java 注解的使用
注解的使用非常簡(jiǎn)單,只需在需要注解的地方標(biāo)明某個(gè)注解即可,例如在方法上注解:
public class Test { @Override public String tostring() { return "override it"; } }例如在類(lèi)上注解: 
@Deprecated public class Test { }所以Java內(nèi)置的注解直接使用即可,但很多時(shí)候我們需要自己定義一些注解,例如常見(jiàn)的spring就用了大量的注解來(lái)管理對(duì)象之間的依賴(lài)關(guān)系。下面看看如何定義一個(gè)自己的注解,下面實(shí)現(xiàn)這樣一個(gè)注解:通過(guò)@Test向某類(lèi)注入一個(gè)字符串,通過(guò)@TestMethod向某個(gè)方法注入一個(gè)字符串。
1.創(chuàng)建Test注解,聲明作用于類(lèi)并保留到運(yùn)行時(shí),默認(rèn)值為default。 
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Test { String value() default "default"; }2.創(chuàng)建TestMethod注解,聲明作用于方法并保留到運(yùn)行時(shí)。 
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface TestMethod { String value(); }3.測(cè)試類(lèi),運(yùn)行后輸出default和tomcat-method兩個(gè)字符串,因?yàn)锧Test沒(méi)有傳入值,所以輸出了默認(rèn)值,而@TestMethod則輸出了注入的字符串。 
@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()); } 感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選