1

Scannotation を使用してクラスファイルをスキャンし、そのクラスの任意の要素に存在する注釈を持つすべてのクラスを取得しています。リフレクションを使用して、メソッドのパラメーターのすべての注釈を見つけることができましたが、後でそのパラメーターを取得できるように、これらの注釈のオブジェクトが必要です (または、それを何と呼びますか)。

これは私のコードの一部であり、必要な注釈を返しますが、それらを操作できません。

    public Set<Class> getParametersAnnotatedBy(Class<? extends Annotation> annotation) {
        for (String s : annotated) { 
        //annotated is set containing names of annotated classes
                    clazz = Class.forName(s); 
                    for (Method m : clazz.getDeclaredMethods()) {
                        int i = 0;
                        Class[] params = m.getParameterTypes();
                        for (Annotation[] ann : m.getParameterAnnotations()) {
                            for (Annotation a : ann) {
                                if (annotation.getClass().isInstance(a.getClass())) {
                                    parameters.add(a.getClass());
                                    //here i add annotation to a set
                                }
                            }
                        }
                    }
                }
            }

次のように、注釈を知っていれば、それで作業できることはわかっています。

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    public String name();
    public int count();
}
// ... some code to get annotations
MyAnnotation ann = (MyAnnotation) someAnnotation;
System.out.println(ann.name());
System.out.println(ann.count());

しかし、これまでのところ、リフレクションを使用してこのようにすることはできませんでした...どのような指示もいただければ幸いです。よろしくお願いします。PS .: フィールドの Field 、メソッドの Method などのパラメータのオブジェクトを取得する方法はありますか?

4

1 に答える 1

1

を使用する必要がありますa.annotationType。アノテーションで getClass を呼び出すと、実際にはそのProxy Classを取得しています。annotationType実際のクラスを取得するには、の代わりに呼び出す必要がありますgetClass

if (annotation.getClass() == a.annotationType()) {
            parameters.add(a.annotationType());
            // here i add annotation to a set
        }
于 2012-05-08T18:03:52.523 に答える