How to get annotation by extracting exception method in Java?

This time I want to get an annotation from an abandoned exception. My sample code is as follows:

public class P {

    @MyAnnotation(stringValue = "FirstType", intValue = 999)
    public void test() throws Exception {
        // ...
        throw new NullPointerException();
   }

    @MyAnnotation(stringValue = "SecondType", intValue = 111)
    public void test(int a) throws Exception {  
        // ...
       throw new NullPointerException();
    }
}

The above class contains 2 methods, and both of them throw a NullPointerException.

Now I can use callerElement to restore the exception and know the package name, class name and line number that cause the exception. Here is my code:

public class CallP {
    public static void main(String[] argv){
        P class_p = new P();

        StackTraceElement[] callerElement = null;
        try{
            class_p.test();
        }catch(Exception e){
            callerElement = e.getStackTrace();
            System.out.println(callerElement[0].toString());
        }
   }
}

In my console window, I see a message

StackoverflowQuestion.P.test (P.java:9)

My questions: 1. How to get annotation in the catch section? 2. When overloading a method (in class P, I have two methods called test), how do I get the annotation?

These are all my questions. Thanks for taking the time to read.

+5
1

getClassName getMethodName(), , , .

: Class.forName(...), klass.getMethod(...) getDeclaredMethod(...) , method.getAnnotations() . IMO, getMethod(String name, Class<?>... parameterTypes) , Type, .

.. . , . , , . , , , , . , , , , , .

+3

All Articles