import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target({ElementType.FIELD}) //註解應用類型 @Retention(RetentionPolicy.RUNTIME) // 註解的類型 public @interface FieldInterface { String name() default ""; }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented // 標記在生成javadoc時是否將註解包含進去,無關緊要 @Target({ElementType.METHOD}) //註解應用類型 @Retention(RetentionPolicy.RUNTIME) // 註解的類型 public @interface MethodInterface { String name() default ""; }
public class TestClass { @FieldInterface(name = "字段註解") private String name = "ls"; private Constructor<?>[] declaredConstructors; @MethodInterface(name = "方法註解") public void isNot() { } }
//方法註解測試 public void getMethodAnnotationValue() { // 獲取全部的方法 Method[] name = TestClass.class.getDeclaredMethods(); for (Method str : name) { // 判斷是否方法上存在註解 boolean annotationPresent = str.isAnnotationPresent(MethodInterface.class); if (annotationPresent) { // 獲取自定義註解對象 MethodInterface methodAnno = str.getAnnotation(MethodInterface.class); // 根據對象獲取註解值 String isNotNullStr = methodAnno.name(); System.out.println(isNotNullStr); } } } //屬性註解測試 public void getFieldAnnotationValue() throws NoSuchFieldException, SecurityException { // 獲取全部的字段 Field[] fields = TestClass.class.getDeclaredFields(); for (Field f : fields) { // 判斷字段註解是否存在 boolean annotationPresent2 = f.isAnnotationPresent(FieldInterface.class); if (annotationPresent2) { FieldInterface name = f.getAnnotation(FieldInterface.class); // 獲取註解值 String nameStr = name.name(); System.out.println(nameStr); } } }
public static void main(String[] args) throws NoSuchFieldException, SecurityException { TestClass c = new TestClass(); // 獲取方法上的註解值 c.getMethodAnnotationValue(); // 獲取字段上的註解值 c.getFieldAnnotationValue(); }
輸出:java
方法註解 字段註解