如何通过反射从方法中获取注释

发布于 2025-02-09 03:42:28 字数 484 浏览 1 评论 0原文

假设

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-02-16 03:42:28

只需获取注释使用getClass()的实例类型。这将返回代理类,因为它是在运行时生成的。此实例将实现注释类型。因此,您可以使用getInterfaces()获得它。

s.getClass().getInterfaces()[0]

然后,您可以在返回的class实例上调用getsimplename()

Just get the Annotation instance's type with getClass(). This will return a proxy class because it is generated at runtime. This instance will implement the annotation type. So you can get it with getInterfaces().

s.getClass().getInterfaces()[0]

You can then call getSimpleName() on the Class instance returned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文