如何通过反射从方法中获取注释
假设
public class A {
@Deprecated
public void f() {}
}
我想通过反射获得方法f()的所有注释。
我尝试的是:
public static void main(String[] args) {
Class c = A.class;
Method[] methods = c.getDeclaredMethods();
String s = methods[0].getDeclaredAnnotations()[0].toString();
System.out.println(s);
}
问题在于它打印了注释的全名 - @java.lang.deprecated()
是否有任何方法可以仅获得注释的简短形式(@depreced或defected)?
Suppose there is a class
public class A {
@Deprecated
public void f() {}
}
I want to get all the annotations of the method f() through reflection.
What I tried:
public static void main(String[] args) {
Class c = A.class;
Method[] methods = c.getDeclaredMethods();
String s = methods[0].getDeclaredAnnotations()[0].toString();
System.out.println(s);
}
The problem is that it prints full name of the annotation - @java.lang.Deprecated()
Is there any way to get only short form of the annotation(@Deprecated or just Deprecated)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需获取
注释
使用getClass()
的实例类型。这将返回代理类,因为它是在运行时生成的。此实例将实现注释类型。因此,您可以使用getInterfaces()
获得它。然后,您可以在返回的
class
实例上调用getsimplename()
。Just get the
Annotation
instance's type withgetClass()
. This will return a proxy class because it is generated at runtime. This instance will implement the annotation type. So you can get it withgetInterfaces()
.You can then call
getSimpleName()
on theClass
instance returned.