0

我有 3 种不同类型的自定义注释。假设它们是 Annotation1、Annotation2、Annotation3。

我将这 3 个注释应用于我班上的一些字段。现在我正在提取/获取分配了这 3 个注释的所有字段。所以为此我写了一个方法

public List<Field> getAnnotation1Fields(Annotation1 argAnnotation1){
     // Code to extract those fields...
}

因此,对于我的 3 个注释,我需要编写 3 种不同的方法,例如

public List<Field> getAnnotation2Fields(Annotation2 argAnnotation2){
     // Code to extract those fields...
}

public List<Field> getAnnotation3Fields(Annotation3 argAnnotation3){
     // Code to extract those fields...
}

在上述方法中,提取逻辑相同,但参数类型不同(Argument)。这里我的问题是如何在单个注释上调用这三种方法......?这样就可以为任何类型的注解(包括我们的自定义注解)调用一个通用方法。

4

4 回答 4

0

你可以用这个简单的方法来做到这一点:

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationType) {
    Field[] declaredFields = clazz.getDeclaredFields();
    List<Field> annotatedFields = new LinkedList<>();
    for(Field field : declaredFields) {
        if(field.getAnnotation(annotationType) != null)
            annotatedFields.add(field);
    }
    return annotatedFields;
}

使用示例:

getAnnotatedFields(TestClass.class, Deprecated.class);
于 2013-09-18T07:26:10.220 回答
0

public List<Field> getAnnotatedFields(java.lang.annotation.Annotation annotation)

或者

public List<Field> getAnnotatedFields(Class<? extends Annotation> annotationType)

取决于你有什么实例(第一个)或类型(第二个)。

于 2013-09-18T07:17:55.897 回答
0

使用方法泛型 - 您可以为方法和类定义变量类型参数,如下所示:

public <T> List<Field> getAnnotationFields(T argAnnotation) {
  // Get fields with annotation type T
}

然后你可以很容易地调用它:

Annotation3 thingy = ...;
getAnnotationFields(thingy); // Extracts fields for Annotation3
于 2013-09-18T07:15:35.153 回答
0

我希望这更接近您的需求:

static <A extends Annotation> Map<String,A> getField2Annotation(
  Class<?> declaringClass, Class<A> annotationType) {

  Field[] fields=declaringClass.getDeclaredFields();
  Map<String, A> map=Collections.emptyMap();
  for(Field f:fields) {
    A anno=f.getAnnotation(annotationType);
    if(anno!=null) {
      if(map.isEmpty()) map=new HashMap<String, A>();
      map.put(f.getName(), anno);
    }
  }
  return map;
}

然后你可以做这样的事情:

public class Example {
  @Retention(RetentionPolicy.RUNTIME)
  @interface Foo { String value() default "bar"; }

  @Foo static String X;
  @Foo("baz") String Y;

  public static void main(String[] args) {
    Map<String, Foo> map = getField2Annotation(Example.class, Foo.class);
    for(Map.Entry<String,Foo> e:map.entrySet()) {
      System.out.println(e.getKey()+": "+e.getValue().value());
    }
  }
}
于 2013-09-18T11:36:28.417 回答