Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get annotation by retrieving exception method in Java?

This time I want to get the annotation from the thrown exception. My example code is like this:

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 contain 2 methods, and both of them throw NullPointerException.

Now I can use callerElement to retreive the exception and know the package name, class name, and line number which 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 can see the message

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

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

That's all my questions. Thanks for spending time on reading.

like image 982
Charles Wu Avatar asked Jan 17 '11 04:01

Charles Wu


1 Answers

You can use getClassName and getMethodName(), to get the class and method name, and then use reflection to get the annotation.

Hint: Class.forName(...) then, klass.getMethod(...) or getDeclaredMethod(...) or any other variant, then method.getAnnotations() or other variant. IMO, getMethod(String name, Class<?>... parameterTypes) suits your need, you can pass the parameterType to get the desired method.

Note: There is no way we can find that out. As the only difference is, the line number. And I doubt, if we can make use of that to get the desired method and its annotations. So, the only solution coming to my mind is to avoid overloading altogether in this case, and name the test methods uniquely. Of course, it would be a work around, but don't you think the name should be descriptive enough to tell what's going to be tested in there.

like image 91
Adeel Ansari Avatar answered Nov 20 '22 11:11

Adeel Ansari