Java 注释可以扩展/解析为许多注释吗?
我有一组经常使用的 Java 注释,如下所示:
@SomeAnnotation(Something)
@SomeOtherAnnotation
@SomeLastAnnotation(SomethingElse)
class Foo
{
/* ... */
}
由于我经常一起使用所有这些注释,并且我可能必须在偶尔使用它们的地方添加它们,所以我想创建一个我可以使用新的注释。然后,该注释应该“解析”为我在某处定义的所有注释。
@MySuperAnnotation
class Foo
{
/* ... */
}
如何声明 @MySuperAnnotation
以便它“解析”所有其他注释?
I have a set of Java annotation that I quite frequently use, like this:
@SomeAnnotation(Something)
@SomeOtherAnnotation
@SomeLastAnnotation(SomethingElse)
class Foo
{
/* ... */
}
As I use all these annotations together quite often, and I may have to add to them in everywhere they are used once in a while, I would like to create a new annotation that I can use instead. This annotation should then "resolve" to all the annotations that I define somewhere.
@MySuperAnnotation
class Foo
{
/* ... */
}
How do I declare @MySuperAnnotation
such that it "resolves" to all the other annotations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,没有办法。但如果您使用 spring (>= 3.0),则可以使用自定义注释。简单示例此处。
In general, there is no way. But if you are using spring ( >= 3.0 ) it is possible with custom annotations. Simple example here.
您可以使用 AspectJ 并使用声明注释指令来完成此操作: http:// /www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-declare.html
在您的上下文中,这应该有效:
You can do it with AspectJ with the declare annotation instruction: http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-declare.html
in your context, this should work:
如果不重写所有查找原始注释的工具和反射代码,您就无法做到这一点。
(或者,正如奥利弗建议的那样,您可以对编译后的 .class 文件进行后处理,以用不同的内容替换注释——据我所知,没有任何工具可以自动为您执行此操作)。
You can't do that, not without rewriting all of the tools and reflection code that looks for the original annotations.
(Or, as Oliver suggests, you could postprocess the compiled .class files to replace the annotations with something different -- not that I know of any tools that will do that for you automatically).