当你获得异常(stacktrace)时,有没有办法找到有关方法的其他信息? 我需要完全注释。如何获取方法名称和类名是可以理解的。
答案 0 :(得分:3)
如果获得堆栈跟踪,您始终可以获取有关类,其方法及其注释的信息。您需要编写一些额外的代码来获取该信息;您需要从堆栈跟踪元素中获取方法,然后使用反射实现方法并获取其注释。
以下是一些示例代码,演示了如何从堆栈跟踪中获取注释信息。相关代码位于方法printAnnotationsFromStacktrace()
:
@Ignore
public class SimpleTests2 {
@Ignore
@Deprecated
public static void main(String[] args) throws ParseException, ClassNotFoundException {
System.out.println(numUnique(new double[]{1.0, 1.0, 2.0, 3.0, 4.0, 3.0}));
}
@SuppressWarnings("test")
private static int numUnique(double[] list) throws ClassNotFoundException {
int unique = 0;
for (int i = 0; i < list.length; i++) {
boolean existsBefore = false;
for (int j = i - 1; j >= 0; j--) {
if (list[i] == list[j]) {
existsBefore = true;
break;
}
}
if(!existsBefore) {
unique++;
}
}
printAnnotationsFromStacktrace();
return unique;
}
private static void printAnnotationsFromStacktrace() throws ClassNotFoundException {
StackTraceElement[] stacktraces = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTraceElement : stacktraces) {
Class<?> aClass = Class.forName(stackTraceElement.getClassName());
System.out.println(aClass);
printAnnotation("\t%s\n", aClass.getAnnotations());
String methodName = stackTraceElement.getMethodName();
Method[] methods = aClass.getMethods();
for(Method method : methods) {
if(method.getName().equals(methodName)) {
System.out.printf("\t%s\n", method);
printAnnotation("\t\t%s\n", method.getDeclaredAnnotations());
}
}
}
}
private static void printAnnotation(String pattern, Annotation[] annotations) {
for(Annotation annotation : annotations) {
System.out.printf(pattern, annotation);
}
}
}
如果运行此代码,您将看到带有相应注释的类名的打印以及堆栈跟踪方法及其注释。像这样:
class java.lang.Thread
public java.lang.StackTraceElement[] java.lang.Thread.getStackTrace()
class SimpleTests2
@org.junit.Ignore(value="")
class SimpleTests2
@org.junit.Ignore(value="")
class SimpleTests2
@org.junit.Ignore(value="")
public static void SimpleTests2.main(java.lang.String[]) throws java.text.ParseException,java.lang.ClassNotFoundException
@org.junit.Ignore(value="")
@java.lang.Deprecated(forRemoval=false, since="")