Edison Miranda
Edison Miranda

Reputation: 333

How to get annotation from method through reflection

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)?

Upvotes: 1

Views: 975

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280170

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.

Upvotes: 1

Related Questions