Java利用反射獲取類中字段和方法註解的值

1、自定義註解

一、字段註解

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 "";
}

2、建立實體類

public class TestClass {
 
@FieldInterface(name = "字段註解")
private String name = "ls";
private Constructor<?>[] declaredConstructors;
 
   @MethodInterface(name = "方法註解")
   public void isNot() {
 
   }
}

3、獲取註解值

//方法註解測試
	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);
			}
		}
	}

4、測試

public static void main(String[] args) throws NoSuchFieldException, SecurityException {
     TestClass c = new TestClass();

     // 獲取方法上的註解值
     c.getMethodAnnotationValue();
 
     // 獲取字段上的註解值
     c.getFieldAnnotationValue();
 
}

輸出:java

方法註解
字段註解
相關文章
相關標籤/搜索