标记接口还是注释?
我需要将一些类标记为可调用 - 只是告诉我可以使用反射调用该类的方法。但我不喜欢仅出于此目的而使用空接口的想法。这可以通过注释来完成,并且仍然保留下面示例中的行为吗? (我从未创建过自己的注释,因此对它们并不深入熟悉)
示例
class ClassOne implements Invokable {
}
class ClassTwo implements Invokable {
}
void someMethod(Invokable inv) {
}
I need to mark some classes as Invokable - just to tell I can invoke methods of the class using reflection. But I don't like the idea of having an empty interface just for this purpose. Can this be done with annotations and still preserve behaviour on the example below? (I have never created my own annotations, so I'm not familiar with them in depth)
Example
class ClassOne implements Invokable {
}
class ClassTwo implements Invokable {
}
void someMethod(Invokable inv) {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于
someMethod
,您无法使用注释。也许稍后您会发现Invokable
无论如何都可能需要有用的方法。另外,在重新发明轮子之前,请务必检查现有的接口,例如 Callable、Future 等。
Because of
someMethod
, you can't use annotations. Perhaps later you'll find thatInvokable
may need useful methods anyway.Also, be sure to check out already existing interfaces like
Callable
,Future
etc. before you re-invent the wheel.您可以通过 Class.getAnnotations() 获取类的注释并搜索您的 Invokable 注释。然后你就可以获取你想要调用的方法,并调用它。
You can get the annotations of a class mit Class.getAnnotations() and search for your Invokable annotation. Then you can get the method you want to invoke, and invoke it.
该决定取决于您将如何使用这些类。如果你有很多类,有些是可调用的,有些不是,那么使用注释可能会更好,只需传递对象/类并检查注释即可。如果您知道要传递的类都是可调用的,那么您可以使用标记接口。
即假设您只想保留行为而不是方法:-)
the decision would depend on how you are going to use these classes. if you have many classes some Invokable and some not, you may be better off with annotations, just pass the objects/ classes and check for the annotation. if you know the classes you would be passing would all be Invokable, you could go with a marker interface.
i.e. assuming you only want to preserve the behaviour and not the method :-)