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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With