Can you limit annotation target to be subclasses o

2020-08-19 10:12发布

问题:

Can you limit that a target of an annotation must be of a certain class?

I want to create a new validation Constraint to limit file types that are uploaded. The constraint annotation must only go on a MultipartFile property, not on String or anything like that. How do I limit this?

回答1:

Not at compile-time; the only restrictions available for annotation placement are by element type (method, class, etc.).



回答2:

Yes, this is possible (and was possible when the question was asked).

As a general rule, when working with annotations you need to use an annotation processor. You can write an annotation processor that issues errors whenever an annotation is written in a disallowed location.

If your question is whether this is possible with plain javac and no annotation processor, then the answer is "no".