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

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

问题描述

我写了一个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?

感谢您的帮助!

推荐答案

您可以在一个的annotation处理器(你将不得不使用的如果你想Java 5的支持私有API )。您可以使用梅萨您从<一个得到href=\"http://java.sun.com/javase/6/docs/api/javax/annotation/processing/ProcessingEnvironment.html\">ProcessorEnvironment传递给init。

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 注解插件确实有扩展点,允许在IDE中更好地整合,如果你想提供自定义的支持。)它会支付检查与常用的工具,特别是如果你需要支持任意的开发环境。

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天全站免登陆