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

如何在Java中通过检索异常方法获取注释?,java,exception,annotations,Java,Exception,Annotations,这次我想从抛出的异常中获取注释。 我的示例代码如下所示: public class P { @MyAnnotation(stringValue = "FirstType", intValue = 999) public void test() throws Exception { // ... throw new NullPointerException(); } @MyAnnotation(stringValue = "Seco

这次我想从抛出的异常中获取注释。 我的示例代码如下所示:

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();
    }
}
上面的类包含2个方法,它们都抛出NullPointerException

现在,我可以使用CallRelation检索异常,并知道导致异常的包名、类名和行号。这是我的密码:

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());
        }
   }
}
在我的控制台窗口中,我可以看到消息

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

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

这就是我所有的问题。感谢您花时间阅读。

您可以使用and获取类和方法名称,然后使用反射获取注释

提示:
Class.forName(…)
然后,
klass.getMethod(…)
getDeclaredMethod(…)
或任何其他变体,然后是
method.getAnnotations()
或其他变体。IMO,适合您的需要,您可以传递参数类型以获得所需的方法


注意:我们无法找到答案。因为唯一的区别是行号。我怀疑,我们是否可以利用它来获得所需的方法及其注释。因此,我想到的唯一解决方案是在这种情况下完全避免重载,并对测试方法进行唯一命名。当然,这将是一项工作,但你不认为这个名字应该具有足够的描述性,足以说明将在那里测试什么。

嗨,阿德尔·安萨里。我可以使用callerement[0].getMethodName()获取方法名。然而,我不知道哪一个是我想要的(我有两个“test()”)。@查尔斯:是的,你是对的。我们不可能找到答案。因为唯一的区别是行号。我怀疑,我们是否可以利用它来获得所需的方法及其注释。