首先注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FirstAnnotation {
String value() default "";
}
第二注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SecondAnnotation {
String value() default "";
}
用例:
public class Test {
@SecondAnnotation("second annotation")
@FirstAnnotation("first annotation")
private String annotatedField1 = "value of field 1";
@SecondAnnotation("second annotation")
@FirstAnnotation("first annotation")
private String annotatedField2 = "value of field 2";
@SecondAnnotation("second annotation")
private String annotatedField3 = "value of field 3";
@FirstAnnotation("first annotation")
private String annotatedField4 = "value of field 4";
// Sample
public static void processAnnotatedFields(final Object obj) throws IllegalArgumentException, IllegalAccessException {
for (final Field field : getFieldsFornAnotation(obj, FirstAnnotation.class)) {
// Do something with fields that are annotated with @FirstAnnotation
final FirstAnnotation an = field.getAnnotation(FirstAnnotation.class);
System.out.print("@" +an.annotationType().getSimpleName()+ "(" +an.value()+ "): ");
System.out.println(field.getName()+ " = '" +field.get(obj)+ "'");
}
System.out.println();
for (final Field field : getFieldsFornAnotation(obj, SecondAnnotation.class)) {
// Do something with fields that are annotated with @SecondAnnotation
final SecondAnnotation an = field.getAnnotation(SecondAnnotation.class);
System.out.print("@" +an.annotationType().getSimpleName()+ "(" +an.value()+ "): ");
System.out.println(field.getName()+ " = '" +field.get(obj)+ "'");
}
}
/**
* Collect object fields annotated with "annotationClass"
* This can be saved in static map to increase performance.
*/
private static final Set getFieldsFornAnotation(final Object o, final Class extends Annotation> annotationClass) {
final Set fields = new LinkedHashSet();
if (o == null || annotationClass == null)
return fields;
for (final Field field : o.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(annotationClass)) {
field.setAccessible(true);
fields.add(field);
}
}
return fields;
}
public static void main(final String[] args) throws IllegalArgumentException, IllegalAccessException {
processAnnotatedFields(new Test());
}
}
结果/输出:
@FirstAnnotation(first annotation): annotatedField1 = 'value of field 1'
@FirstAnnotation(first annotation): annotatedField2 = 'value of field 2'
@FirstAnnotation(first annotation): annotatedField4 = 'value of field 4'
@SecondAnnotation(second annotation): annotatedField1 = 'value of field 1'
@SecondAnnotation(second annotation): annotatedField2 = 'value of field 2'
@SecondAnnotation(second annotation): annotatedField3 = 'value of field 3'