强制带注释的类包含带注释的字段 [英] Force annotated Class to contain annotated Field

查看:31
本文介绍了强制带注释的类包含带注释的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以(在编译时)强制带注释的类具有带注释的字段?

Is it possible to force (at compile-time) an annotated Class to have a an annotated Field?

我有这个注释:

@Target(value = ElementType.TYPE)
@interface MyClass {}

@Target(value = ElementType.FIELD)
@interface MyField {}

现在我希望这样的类的编译失败:

and now I would like that the compilation of a Class like this fails:

@MyClass
class Customer {

}

而这应该有效:

@MyClass
class Customer {
   @MyField
   String text;
}

推荐答案

是的,使用 apt(注释处理工具).

Yes, using apt (annotation processing tool).

但对于如此简单的任务来说,这将是一种矫枉过正.

But for such simply tasks it will be an overkill.

您可以制作一些在应用程序启动时触发的侦听器并检查此要求.

You can make some listener that is triggered on application startup and checks this requirement.

最后,您可以通过假设合理的默认值来避免这种情况 - 即,如果类被注释,则考虑所有字段也被注释,使用默认值.

Finally, you can avoid this by assuming reasonable defaults - i.e. if the class is annotated, then consider all fields annotated as well, with the default values.

这篇关于强制带注释的类包含带注释的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆