是否可以使注释适用于特定类型的字段?

use*_*882 4 java annotations

例如,在下面的注释中:

@Target(ElementType.FIELD) 
@Retention(RetentionPolicy.RUNTIME)
public @interface EndOfTheCurrentDay {
    //some staff
}
Run Code Online (Sandbox Code Playgroud)

显然,我们不能将注释应用于类型的字段,例如,Integer。但在它的实现方式中,注释的使用可能是不安全的。如何防止将注释应用到除 之外的字段java.util.Date?有可能吗?

Ran*_*niz 5

不,您无法可靠地限制这一点并在编译期间生成错误 - 可以禁用注释处理器。如果您想绝对确定,则需要在处理注释时在运行时验证它:

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
}
Run Code Online (Sandbox Code Playgroud)

  • @user3663882注释本身什么也不做,它们将数据附加到字段/参数/方法/类。 (2认同)