我可以根据被注释的字段的类型生成编译时错误吗 [英] Can I generate a compile time error based on the type of the field being Annotated

查看:24
本文介绍了我可以根据被注释的字段的类型生成编译时错误吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个看起来像这样的Java注解:

I have written a java annotation that looks like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)  // can I further limit this to only fields of type DomainObject?
public @interface Owns {
}

短暂环顾四周后,我看不出是否有办法进一步限制此注释的使用,以便只能注释特定类型的字段.这个注解是针对我们的域定制的,只能用于我们的基域对象类的实例.

After briefly looking around I couldn't see if there was a way to further limit the usage of this annotation so that only fields of a specific type could be annotated. This annotation is custom to our domain and can only be used on instances of our base domain object class.

有人知道如何在编译时强制执行此操作吗?

Does anyone know how to enforce this at compile time?

感谢您的帮助!

推荐答案

您可能会在 注释处理器(您必须使用 私有 API(如果您需要 Java 5 支持).您可以使用您获得的 Messager来自传递给 init 的 ProcessorEnvironment.

You could emit an error in an annotation processor (you'll have to use a private API if you want Java 5 support). You can use the Messager you get from the ProcessorEnvironment passed to init.

这有多有效可能取决于您的工具链.如果您使用 javac 通过命令行编译应该没问题或通过构建脚本.在我的 Eclipse 版本中,我必须为项目手动启用注释处理器(通过项目设置)并且错误没有出现在任何明显的地方.(JDT 注释插件确实具有扩展点,如果您想提供自定义支持.)检查常用工具是值得的,特别是如果您需要支持任意开发环境.

How effective this is might depend on your tool chain. It should be fine if you use javac to compile by the command line or via a build script. In my version of Eclipse, I had to enable annotation processors manually for the project (via project settings) and errors didn't appear anywhere obvious. (The JDT annotation plugins do have extension points that allow better integration with the IDE if you want to provide custom support.) It would pay to check with commonly used tools, especially if you need to support arbitrary development environments.

这篇关于我可以根据被注释的字段的类型生成编译时错误吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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