实现接口的Java类可以自动继承注释吗?
假设我有一个带有一些注释的接口,例如:
@SpecialClass
public interface IFoo { /* ... */ }
假设我创建一个实现该接口的类:
public class Foo implements IFoo { /* ... */ }
类 Foo
是否有可能以某种方式“继承”或自动复制全部或部分内容来自 IFoo
及其成员的注释(例如自动将 Foo
注释为 @SpecialClass
等)?
这对于实现 Web 服务类(例如,由 JAX-WS“wsimport”工具生成的类)来说非常方便,只需实现其带注释的接口,而无需显式地将接口注释复制到实现类(例如 javax.jws. WebService
、javax.xml.ws.RequestWrapper
等)。
Suppose I had an interface with some annotation(s), for example:
@SpecialClass
public interface IFoo { /* ... */ }
And suppose I make a class that implements the interface:
public class Foo implements IFoo { /* ... */ }
Is it possible for class Foo
to somehow "inherit" or automatically copy all or some of the annotations from IFoo
and its members (e.g. automagically annotate Foo
as @SpecialClass
, etc.)?
This would be convenient for implementing web service classes (e.g. those generated by the JAX-WS "wsimport" tool) by just implementing their annotated interfaces without explicitly having to copy the interface annotations to the implementing class (e.g. javax.jws.WebService
, javax.xml.ws.RequestWrapper
, etc).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:我将这个答案留在这里供一般信息和未来的读者使用,但 Andreas 指出了我错过的 Javadoc 的重要部分:
换句话说,在这种情况下它不会有帮助。当然,只有当您可以控制注释本身时,它才有用。
我怀疑真正的答案是您只需在各处应用注释即可。如果您担心忘记一个,您可能需要编写一个单元测试来查找所有类(我意识到说起来容易做起来难)并检查实现给定接口的所有类是否存在注释。
您是否尝试过应用
继承
对SpecialClass
注释本身进行注释?这当然听起来正是您想要的。
EDIT: I'm leaving this answer here for general information and future readers, but Andreas pointed out an important bit of the Javadoc which I'd missed:
In other words, it wouldn't help in this situation. Also it's only useful if you have control over the annotation itself, of course.
I suspect the real answer is that you simply have to apply the annotation everywhere. If you're worried about forgetting one, you might want to write a unit test which finds all your classes (easier said than done, I realise) and checks that the annotation is present for all classes implementing the given interface.
Have you tried applying the
Inherited
annotation to theSpecialClass
annotation itself?That certainly sounds like exactly what you want.