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

查看:30
本文介绍了为什么不能在 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".

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

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