Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generics provide information which only exists at compile-time; at run-time all the information is lost. When compiling code with generics, the compiler will strip out all the generic type information and insert casts as necessary. For example,</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add("test"); String s = list.get(0); </code></pre> <p>will end up being compiled as</p> <pre><code>List list = new ArrayList(); list.add("test"); String s = (String) list.get(0); </code></pre> <p>with the compiler automatically adding the cast in the third line.</p> <p>It looks to me like you are trying to use generics for run-time type safety. This is not possible. In the line</p> <pre><code>validator.validate(field, a, target); </code></pre> <p>there is no way for the compiler to know what subtype of <code>Annotation</code> the validator expects.</p> <p>I think the best thing to do is to drop the type variable <code>A</code> and declare your interface as follows:</p> <pre><code>interface AnnotatedFieldValidator { void validate(Field f, Annotation annotation, Object target); Class&lt;? extends Annotation&gt; getSupportedAnnotationClass(); } </code></pre> <p><code>addValidator</code> would then also lose its parameterised type, i.e.</p> <pre><code>public void addValidator(AnnotatedFieldValidator v) { validators.put(v.getSupportedAnnotationClass(), v); } </code></pre> <p>The downside of this is that you will have to check that your validators are being passed an annotation of a class that they can validate. This is easiest to do in the code that calls the validator, e.g.</p> <pre><code>if (validator.getSupportedAnnotationClass().isInstance(a)) { validator.validate(field, a, target); } else { // wrong type of annotation, throw some exception. } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload