標籤:
定義:
package com.dxz.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//定義註解@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.LOCAL_VARIABLE })@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation { // 定義兩個成員變數 String name() default "jack"; int age() default 22;}
測試:
package com.dxz.annotation;import java.lang.annotation.Annotation;/* * 獲得註解資訊要注意,當前註解一定要保留在RUNTIME * * 獲得註解資訊方法: * 1.getAnnotations() * 調用註解成員變數 * 1.假設註解對象ann,調用成員變數方式:ann.name(); * 2.與調用類方法類似 */public class TestAnnotationInfo { public static void main(String[] args) { TestAnnotationInfo tai = new TestAnnotationInfo(); try { tai.getInfo(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } @MyAnnotation(name = "zhangxun", age = 20) public void getInfo() throws NoSuchMethodException, SecurityException { // 擷取TestAnnotationInfo對象的getInfo()方法中包含的所有註解 @MyAnnotation Annotation[] annos = TestAnnotationInfo.class.getMethod("getInfo") .getAnnotations(); // 遍曆annos數組 for (Annotation ann : annos) { // ann就是一個Annotation 對象 // 判斷當前ann是否是MyAnnotation註解類型 if (ann instanceof MyAnnotation) { System.out.println(ann); System.out.println(((MyAnnotation) ann).name()); System.out.println(((MyAnnotation) ann).age()); } } }}
java註解annotation,自訂註解