如何通过在Java中检索异常方法来获取注释?

Cha*_* Wu 6 java annotations exception

这次我想从抛出的异常中获取注释.我的示例代码是这样的:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的类包含2个方法,它们都抛出NullPointerException.

现在我可以使用callerElement来检索异常,并知道导致异常的包名,类名和行号.这是我的代码:

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());
        }
   }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制台窗口中,我可以看到该消息

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

我的问题是1.如何在catch子句中获取注释?2.当方法重载时(在P类,我有两个方法叫test),如何获取注释?

这就是我的全部问题.感谢您花时间阅读.

Ade*_*ari 3

您可以使用getClassNamegetMethodName(), 来获取类和方法名称,然后使用反射来获取注释。

提示: Class.forName(...) thenklass.getMethod(...)getDeclaredMethod(...)或任何其他变体,thenmethod.getAnnotations()或其他变体。IMO,getMethod(String name, Class<?>... parameterTypes)适合您的需要,您可以传递parameterType来获取所需的方法。

注意:我们无法发现这一点。唯一的区别是行号。我怀疑我们是否可以利用它来获取所需的方法及其注释。因此,我想到的唯一解决方案是在这种情况下完全避免重载,并唯一地命名测试方法。当然,这将是一种解决方法,但是您不认为该名称应该具有足够的描述性来告诉其中将要测试的内容吗?