Java中的注解概念
引用此链接:
一些开发人员认为 Java 编译器可以理解该标签并 相应地工作。这是不对的。标签实际上没有任何意义 Java 编译器或运行时本身。有一些工具可以 解释这些标签
。
如果注释中包含的信息只是元数据,那么如果注释错误,为什么我的代码无法编译?那个特定的注释应该被简单地忽略吧?
编辑:
只是提供一个示例...泽西岛上的一个简单的 JAX-RS Web 服务使用如下注释:
@Path("mypath")
现在,如果我将其更改为:
@Paths("mypath")
或者
@Path(123)
它不应该阻止我根据上面的链接编译代码...
To quote this link :
Some developers think that the Java compiler understands the tag and
work accordingly. This is not right. The tags actually have no meaning
to the Java compiler or runtime itself. There are tools that can
interpret these tags
.
If the information contained in the annotation is only metadata, why wont my code compile if I annotate wrongly ? That particular annotation should be simply ignored right ?
Edit :
Just to provide an example... A simple JAX-RS web service on Jersey uses an annotation like :
@Path("mypath")
Now, if I change this to :
@Paths("mypath")
OR
@Path(123)
it should NOT stop me from compiling the code according to the above link...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这篇文章至少有一些注释是错误的。就像
@SuppressWarnings
和@Override
一样,编译器确实具有非常具体的知识。事实上,这篇文章本身就指出了这一点:如果“标签实际上对 Java 编译器没有意义”,那么编译器如何使用它,我不知道......
此外,即使对于编译器不附加任何语义的注释含义< /em> ,它仍然会验证当您尝试指定特定参数等时,这些参数对于您正在使用的注释具有合理的名称和类型。
The article is wrong for at least some annotations. Thinks like
@SuppressWarnings
and@Override
the compiler does have very specific knowledge. In fact, the article points this out itself:Quite how it can be used by the compiler if "the tags actually have no meaning to the Java compiler", I don't know...
Additionally, even for annotations that the compiler doesn't attach any semantic meaning to, it will still verify that when you try to specify particular arguments etc, that those arguments have sensible names and types for the annotation you're using.
注释基本上是一种特殊形式的接口,因此编译器必须能够加载注释定义以便对信息进行编码,以便将其包含在类文件中。一旦它进入类文件,类加载器就会将其作为类的一部分加载,以便注释处理工具可以访问该信息。编译器将验证是否仅使用定义的参数,并为未指定的属性提供默认值(并且已定义默认值)。
Annotations are basically a special form of interface, so the compiler has to be able to load the annotation definition in order to encode the information so it can be included in the class file. Once it's in the class file, the class loader will load it as part of the class, so that annotation-processing tools can access the information. The compiler will verify that only defined arguments are used, as well as supplying default values for attributes that aren't specified (and have defaults defined).