简体   繁体   中英

Is there any way to mix or inherit annotation value 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 annotaion from subclass, the anno only contains customized a2, but a1 is only able to get default value, is there any way get an annotation mix all superclass specified fields like {a1:myA1, a2:myA2, a3:defaultValueA3} but not {a1:defaultValueA1,a2:myA2, a3:defaultValueA3} ?


update:

I know annotation is not inheritable, so I tried mix subClass annotation {a1:defaultValueA1, a2:myA2, a3:defaultValueA3} and superClass annotaion {a1:myA1, a2: defalutValueA2, a3:myA3} , my way is get all subClass customized values and copy them to superClass annotation, but the problem is when I get all annotation value from subClass, I can't distiguish which value is user defined and which value is come from default value, anyone have 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's 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.

Annotations aren't inherited according to JavaDoc:

Open Declaration Annotation[] java.lang.Class.getDeclaredAnnotations()

Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM