代码如下,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();
}
}