Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make annotations be applicable to fields of a specific type?

For instance, in the follwing annotation:

@Target(ElementType.FIELD) 
@Retention(RetentionPolicy.RUNTIME)
public @interface EndOfTheCurrentDay {
    //some staff
}

it is obviously that we can't apply the annotation to the field of the type, say, Integer. But in the way it was implemented, the usage of the annotation may be unsafe. How can I prevet applying the annotaion to the field other than java.util.Date? Is it even posible?

like image 415
user3663882 Avatar asked Feb 09 '23 21:02

user3663882


1 Answers

No, you cannot reliably restrict this and generate errors during compilation - annotation processors can be disabled. If you want to be absolutely certain you need to validate it in runtime when you process the annotation:

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
}
like image 137
Raniz Avatar answered May 15 '23 21:05

Raniz