How do I force a Java subclass to define an Annotation?

I am quite sure that this is impossible to do at compile time.

However, this is an obvious task for a "unit"-test. If you have conventions like this that you would like enforced, but which can be difficult or impossible to check with the compiler, "unit"-tests are a simple way to check them.

Another possibility is to implement a custom rule in a static analyzer. There are many options here, too.

(I put unit in scare-quotes, since this is really a test of conventions, rather than of a specific unit. But it should run together with your unit-tests).


You could make an Annotation (e.g. @EnforceAuthor) with @Inherited on the superclass and use compiler annotations (since Java 1.6) to catch up at compile time. Then you have a reference to the subclass and can check if another Annotation (e.g. @Author)) is missing. This would allow to cancel compiling with an error message.


You can do that with JSR 269, at compile time. See : http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api

Edit 2020-09-20: Link is dead, archived version here : https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html