Java注解动态类型转换
我有 2 个 java 注释类型,比如说 XA 和 YA。两者都有一些方法()。我解析源代码并检索 Annotation 对象。现在我想动态地将注释转换为它的真实类型以便能够调用 method()。如果没有 instanceof
语句,我该如何做到这一点?我真的想避免类似开关的源。我需要这样的东西:
Annotation annotation = getAnnotation(); // I recieve the Annotation object here
String annotationType = annotation.annotationType().getName();
?_? myAnnotation = (Class.forName(annotationType)) annotation;
annotation.method(); // this is what I need, get the method() called
?_?意味着我不知道 myAnnotation 类型是什么。我无法将基类用于我的 XA 和 YA 注释,因为不允许注释中的继承。或者有可能以某种方式做吗?
感谢您的任何建议或帮助。
I have 2 java annotation types, let's say XA and YA. Both have some method(). I parse the source code and retrieve Annotation object. Now I'd like to dynamicaly cast the annotation to the real type of it to be able to call the method(). How can I do it without the instanceof
statement? I really want to avoid switch-like source. I need something like this:
Annotation annotation = getAnnotation(); // I recieve the Annotation object here
String annotationType = annotation.annotationType().getName();
?_? myAnnotation = (Class.forName(annotationType)) annotation;
annotation.method(); // this is what I need, get the method() called
?_? means I have no idea what would be myAnnotation type. I cannot use the base class for my XA and YA annotations since the inheritance in annotations is not allowed. Or is it possible to do somehow?
Thanks for any suggestion or help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不使用类型安全的方式来检索注释?
如果找不到您的注释,则返回 null。
请注意,这也适用于字段和方法。
Why don't you use the typesafe way to retrieve your annotation ?
If your annotation can't be found, null is returned.
Please note that this also works with fields and methods.
一种方法是使用方法的名称动态调用该方法:
这种方法风险很大,并且在需要时会完全损害代码重构。
One way is to invoke the method dynamically using the name of it:
This approach is quite risky and totally compromise the code refactoring if needed.