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

空扰寡人 提交于 2019-11-30 18:10:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!