2010-12-29 17 views
1

リフレクションに関連するいくつかのトリッキーなジェネリック型の問題があります。ここにコードがあります。Java汎用型とリフレクション

public @interface MyConstraint { 
    Class<? extends MyConstraintValidator<?>> validatedBy(); 
} 

public interface MyConstraintValidator<T extends Annotation> { 
    void initialize(T annotation); 
} 

/** 
    @param annotation is annotated with MyConstraint. 
*/ 
public void run(Annotation annotation) { 
    Class<? extends MyConstraintValidator<? extends Annotation>> validatorClass = annotation.annotationType().getAnnotation(MyConstraint.class).validatedBy(); 
    validatorClass.newInstance().initialize(annotation) // will not compile! 
} 

上記のrun()メソッドは、次のエラーのためにコンパイルされません。

The method initialize(capture#10-of ? extends Annotation) in the type MyConstraintValidator<capture#10-of ? extends Annotation> is not applicable for the arguments (Annotation) 

ワイルドカードを削除すると、コンパイルされて正常に動作します。可能性のある型式パラメータvalidatorClassの型パラメータを宣言するプロパティの方法は何ですか?

ありがとうございました。

答えて

2

? extends Annotationは、「注釈の任意のサブタイプ」とは異なる「注釈の未知のサブタイプ」を意味します。

方法の初期化は、「注釈の未知のサブタイプを」必要といくつかの点で、未知のサブタイプが今AnotherAnnotationとして知られていると言い、そしてあなたがそうAnotherAnnotationのタイプではないかもしれないアノテーションクラスのオブジェクトを渡すためにしようとしています彼らは互換性がありません。

同様の質問が回答hereでした。

関連する問題