为什么不能在Java中扩展注释? [英] Why is it not possible to extend annotations in Java?

查看:118
本文介绍了为什么不能在Java中扩展注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么Java注释中没有继承,就像Java类一样。我认为它非常有用。

I don't understand why there is no inheritance in Java annotations, just as Java classes. I think it would be very useful.

例如:我想知道给定的注释是否是验证器。通过继承,我可以反复地浏览超类,以了解此注释是否扩展了 ValidatorAnnotation 。否则,我怎么能实现这个目标呢?

For example: I want to know if a given annotation is a validator. With inheritance, I could reflexively navigate through superclasses to know if this annotation extends a ValidatorAnnotation. Otherwise, how can I achieve this?

那么,任何人都可以给我这个设计决定的理由吗?

So, can anyone give me a reason for this design decision?

推荐答案

关于它没有这样设计的原因你可以在 JSR 175 设计常见问题,其中包含:

About the reason why it wasn't designed that way you can find the answer in the JSR 175 Design FAQ, where it says:


为什么不支持注释子类型(其中一个注释类型扩展另一个注释)?

Why don’t you support annotation subtyping (where one annotation type extends another)?

它使注释类型
系统变得复杂,并使其更多
很难写特定工具。

It complicates the annotation type system, and makes it much more difficult to write "Specific Tools".

...

特定工具 - 查询的程序
已知的任意
外部程序的注释类型。 Stub生成器,例如
,属于这一类。
这些程序将读取带注释的
类而不将它们加载到
虚拟机中,但会加载
注释接口。

"Specific Tools" — Programs that query known annotation types of arbitrary external programs. Stub generators, for example, fall into this category. These programs will read annotated classes without loading them into the virtual machine, but will load annotation interfaces.

所以,是的,我想,原因是它只是KISS。无论如何,似乎这个问题(以及许多其他问题)正在作为 JSR 308的一部分进行研究。 ,您甚至可以找到具有此功能的替代编译器,该编译器已由开发Mathias Ricken

So, yes I guess, the reason is it just KISS. Anyway, it seems this issue (along with many others) are being looked into as part of JSR 308, and you can even find an alternative compiler with this functionality already developed by Mathias Ricken.

这篇关于为什么不能在Java中扩展注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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