Java 註解的使用
註解的使用非常簡單,只需在需要註解的地方標明某個註解即可,例如在方法上註解:
public class Test { @Override public String tostring() { return "override it"; } }例如在類上註解:
@Deprecated public class Test { }所以Java內置的註解直接使用即可,但很多時候我們需要自己定義一些註解,例如常見的spring就用了大量的註解來管理對象之間的依賴關係。下面看看如何定義一個自己的註解,下面實現這樣一個註解:通過@Test向某類註入一個字符串,通過@TestMethod向某個方法注入一個字符串。
1.創建Test註解,聲明作用於類並保留到運行時,默認值為default。
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Test { String value() default "default"; } 2.創建TestMethod註解,聲明作用於方法並保留到運行時。
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface TestMethod { String value(); } 3.測試類,運行後輸出default和tomcat-method兩個字符串,因為@Test沒有傳入值,所以輸出了默認值,而@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()); }感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!