例如,在下面的注解中:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EndOfTheCurrentDay {
//some staff
}
很明显,我们不能将注释应用于类型的字段,例如,Integer
。但是在它的实现方式中,注解的使用可能是不安全的。如何防止将注释应用于 java.util.Date
以外的字段?这甚至可能吗?
最佳答案
不,你不能可靠地限制它并在编译期间产生错误——注解处理器可以被禁用。如果你想绝对确定你需要在处理注释时在运行时验证它:
void processAnnotations(Field f) {
EndOfTheCurrentDay annotation = f.getAnnotation(EndOfTheCurrentDay.class);
if(annotation == null) {
return; // Nothing to do
}
if(Date.class.isAssignableFrom(f.getType())) {
throw new Error("The @EndOfTheCurrentDay annotation may only be applied to fields of type Date");
}
// Do something with the field
}
关于java - 是否可以使注释适用于特定类型的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772945/