2010-12-29 17 views
1

Ich habe einige knifflige generische Probleme mit der Reflexion. Hier ist der Code.Java Generic Type und Reflection

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! 
} 

Die run() oben beschriebene Methode wird nicht wegen des folgenden Fehlers kompilieren.

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

Wenn ich die Wildcards entfernen, dann kompiliert und funktioniert einwandfrei. Was wäre die Möglichkeit, den Typparameter für die Variable validatorClass zu deklarieren?

Danke.

Antwort

2

? extends Annotation bedeutet "unbekannter Subtyp der Annotation", die sich von "jeder Subtyp der Annotation" unterscheidet.

Die Initialisierung des Verfahrens „unbekannte Subtyp von Annotation“ erfordert, sagt irgendwann der unbekannte Subtyp jetzt als AnotherAnnotation bekannt ist, und Sie versuchen, ein Objekt der Annotation-Klasse übergeben, die nicht die Art von AnotherAnnotation sein können, so Sie sind nicht kompatibel.

Ähnliche Frage war Antwort here.