gpt4 book ai didi

java - Java中有没有办法混合或继承注释值?

转载 作者:行者123 更新时间:2023-12-02 05:31:25 25 4
gpt4 key购买 nike

我有一个这样的注释

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

目前,当我尝试从子类获取注释时,anno仅包含自定义的a2,但a1只能获取默认值,有没有办法获得注释混合所有父类(super class)指定的字段,例如{a1:myA1 , a2:myA2, a3:defaultValueA3} 但不是 {a1:defaultValueA1,a2:myA2, a3:defaultValueA3}

<小时/>

更新:

我知道注释是不可继承的,所以我尝试混合子类注释{a1:defaultValueA1, a2:myA2, a3:defaultValueA3}和父类(super class)注释{a1:myA1, a2: defalutValueA2 , a3:myA3},我的方法是获取所有子类自定义值并将它们复制到父类(super class)注释中,但问题是当我从子类获取所有注释值时,我无法区分哪个值是用户定义的,哪个值是用户定义的值来自默认值,有人有建议吗?

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[] {}));
}

感谢您的关注。

最佳答案

根据 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.

但是您可以尝试使用 while 循环并使用此方法获取所有声明的注释java.lang.Class.getSuperclass()

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

关于java - Java中有没有办法混合或继承注释值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25133363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com