代碼如下,A、B是兩個注解,Test是測試的demo
package com.rgy.test;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({ FIELD, METHOD })
public @interface A {
String aId();
String aName();
}
package com.rgy.test;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({ FIELD, METHOD })
public @interface B {
String bId();
String bName();
}
package com.rgy.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Test {
@A(aId = "a1", aName = "a1")
@B(bId = "b1", bName = "b1")
private String id;
@A(aId = "a2", aName = "a2")
@B(bId = "b2", bName = "b2")
private String name;
private static void test() {
Field[] declaredFields = Test.class.getDeclaredFields();
for (Field field : declaredFields) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
test();
}
}
你拿到Filed的時候,不要用getAnnotations()這個方法,這是獲取這個Filed上的所有注解,你不好具體處理,你可以使用這個方法
getAnnotation(A.class)
就可以獲取當前Filed上的注解A的對象,然後就可以取到注解裡你想要的屬性了值
A a = getAnnotation(A.class);
String aId = a.aId();
B注解的話,也是類似這麼做