我在网上尝试了很多东西,但似乎没有什么对我有用。我想知道注释方法是否已经@Override
n (与它的值相同default
)。
看看这个例子:
public class AnnoTest {
@Anno
private String something;
public static void main(String[] args) throws NoSuchFieldException, SecurityException, NoSuchMethodException {
Field field = AnnoTest.class.getDeclaredField("something");
field.setAccessible(true);
boolean isDefault= field.getAnnotation(Anno.class).annotationType().getDeclaredMethod("include").isDefault();
System.out.println(isDefault); //returns false
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface Anno {
boolean include() default false;
}
}
由于某种原因,它返回 false。当我将其更改为:
@Anno(include = false)
private String something;
它又回来false
了。有没有办法知道该值是否已在注释中声明?
我知道我可以只比较默认值和它的当前值,但它对我不起作用。我想知道它是否已被宣布。
换句话说,我需要某种神奇的布尔值来执行以下操作:
@Anno
private String something;
返回false
。
@Anno(include = true)
private String something;
返回true
。
@Anno(include = false)
private String something;
返回true
。
这样做的原因是我希望添加一个名为“parent”的方法(到我的注释中)。当一个父级(一个字符串)被声明为注解时,该字段将继承名为 parent 的字段的注解。看看这个例子:
public class AnnoTest {
@Anno(include = false)
private Something something = new Something();
@Anno(parent = "something")
private Something somethingElse = new Something();
public static void main(String[] args) throws NoSuchFieldException, SecurityException, NoSuchMethodException {
AnnoTest test = new AnnoTest();
Field somethingField = AnnoTest.class.getDeclaredField("something");
somethingField.setAccessible(true);
Field somethingElseField = AnnoTest.class.getDeclaredField("somethingElse");
somethingField.setAccessible(true);
Anno anno = somethingElseField.getAnnotation(Anno.class);
if (anno.parent().equals("something")) {
boolean include = somethingField.getAnnotation(Anno.class).include();
test.somethingElse.isIncluded = include;
}
//If not declared it will return true, which it should be false, because "something" field has it false.
boolean include = somethingElseField.getAnnotation(Anno.class).include();
//if somethingElse has declared "include", dominate the value, else keep it from the parent
test.somethingElse.isIncluded = include;
}
public class Something {
boolean isIncluded;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface Anno {
boolean include() default false;
String parent() default "";
}
}