作为参数传递时如何检测字段注释?
How to detect field annotations when passed as parameter?
我有这个代码:
private static class MyObj {
@NoConnection private static Object obj = new Object();
public static boolean test() {
return AnnotationDetector.isAnnotated(obj);
}
}
注释检测器的工作原理如下:
private static class AnnotationDetector {
public static boolean isAnnotated(Object object) {
return object.getClass().isAnnotationPresent(NoConnection.class);
}
}
似乎无法感知传递的对象是否带有注释。如何重写 AnnotationDetector
使其正常工作?
在您的案例中无法检测到注释,因为注释未绑定到值,它们绑定到程序的元素(字段、方法、方法参数等)。您唯一可以做的就是将这样的元素传递给 isAnnotated
方法(称为 AnnotatedElement
):
static class MyObj {
@NoConnection private static Object obj = new Object();
public static boolean test() throws NoSuchFieldException, SecurityException {
return AnnotationDetector.isAnnotated(MyObj.class.getDeclaredField("obj"));
}
}
private static class AnnotationDetector {
public static boolean isAnnotated(AnnotatedElement f) {
return f.isAnnotationPresent(NoConnection.class);
}
}
我有这个代码:
private static class MyObj {
@NoConnection private static Object obj = new Object();
public static boolean test() {
return AnnotationDetector.isAnnotated(obj);
}
}
注释检测器的工作原理如下:
private static class AnnotationDetector {
public static boolean isAnnotated(Object object) {
return object.getClass().isAnnotationPresent(NoConnection.class);
}
}
似乎无法感知传递的对象是否带有注释。如何重写 AnnotationDetector
使其正常工作?
在您的案例中无法检测到注释,因为注释未绑定到值,它们绑定到程序的元素(字段、方法、方法参数等)。您唯一可以做的就是将这样的元素传递给 isAnnotated
方法(称为 AnnotatedElement
):
static class MyObj {
@NoConnection private static Object obj = new Object();
public static boolean test() throws NoSuchFieldException, SecurityException {
return AnnotationDetector.isAnnotated(MyObj.class.getDeclaredField("obj"));
}
}
private static class AnnotationDetector {
public static boolean isAnnotated(AnnotatedElement f) {
return f.isAnnotationPresent(NoConnection.class);
}
}