Is there a way to mix or inherit the meaning of an annotation in Java?

I have an annotation like this

public @interface anno{
    String a1() default "defaultValueA1";
    String a2() default "defaultValueA2";
    String a3() default "defaultValueA3"
}



Class SuperClass{
    @anno(a1="myA1", a3="myA3")
    private String field1; 
}

Class SubClass extends SuperClass(){
    @anno(a2="myA2", a3="defaultValueA3")
    private String field1;
}

      

Currently when I try to get annotation from subclass anno only contains customized a2, but a1 can only get default, is there any way to get annotated mix for all superclasses specified as {a1:myA1, a2:myA2, a3:defaultValueA3}

but not {a1:defaultValueA1,a2:myA2, a3:defaultValueA3}

?


update:

I know the annotation is not inherited, so I tried to add subclass annotation {a1:defaultValueA1, a2:myA2, a3:defaultValueA3}

and superclass annotation {a1:myA1, a2: defalutValueA2, a3:myA3}

, my way is to get all subclass values ​​of subClass and copy them to superClass annotation, but the problem is that I get all annotation value from subClass, I cannot determine which value is user defined and which value is derived from the default, who has a suggestion?

private void mixAnnotaiont(Annotation target, Annotation source){
    Method[] methods = source.annotationType().getMethods();
    Map<String, Object> sourceCfg = AnnotationUtils.getAnnotationAttributes(source);
    for (int i = 0; i < methods.length; i++) {

         // skip default value, but it incorrect, user may specify default value in subClass to overwrite superClass value
        Object defaultValue = methods[i].getDefaultValue();
        String name = methods[i].getName();
        if(sourceCfg.get(name).equals(defaultValue)){
            ignoreProperties.add(name);
        }

    }
    BeanUtils.copyProperties(source, target, ignoreProperties.toArray(new String[] {}));
}

      

Thanks for your attention.

+3


source to share


1 answer


Annotations are not inherited according to JavaDoc:

Open declaration annotation [] java.lang.Class.getDeclaredAnnotations ()

Returns all annotations that are directly present on this element. Unlike other methods in this interface, this method ignores inherited annotations. (Returns a zero-length array if no annotations are directly present on this element.) The caller of this method can modify the returned array; it will not affect the arrays returned by other callers.



But you can try to have a while loop and get all annotations declared using this method java.lang.Class.getSuperclass ()

while(loop thru the super class)
{
   // get declared annotation
}

      

0


source







All Articles