java是一中高级语言,是编译型的语言,也是解释型的语言。现在各种框架类库(Spring、Struts)大量使用java的反射机制。使用反射反射时sun java虚拟机异常的输出形式有点不一样
下面是我的测试代码
static public class Test1
{
public void abc(int a)
{
System.out.println("abc ..." + a);
throw new RuntimeException("tdtd");
}
}
@SuppressWarnings("unchecked")
static void test3() throws Exception
{
Class cls = Test1.class;
Object obj = cls.newInstance();
Method method= cls.getMethod("abc", int.class);
method.invoke(obj, 10);
}
/**
* @param args
*/
public static void main(String[] args) {
try {
// test();
//test2();
test3();
} catch (Exception e) {
StackTraceElement[] elements = e.getStackTrace();
//Throwable cause = e.fillInStackTrace();
//JavaUtil.debugPrint(cause.getClass());
e.printStackTrace();
System.out.println();
e.getCause().printStackTrace();
}
}
其中
e.printStackTrace();
输出如下:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at cn.sh.flyhyp.cherry.InterceptorExecutorRun.test3(InterceptorExecutorRun.java:63)
at cn.sh.flyhyp.cherry.InterceptorExecutorRun.main(InterceptorExecutorRun.java:74)
Caused by: java.lang.RuntimeException: tdtd
at cn.sh.flyhyp.cherry.InterceptorExecutorRun$Test1.abc(InterceptorExecutorRun.java:53)
... 6 more (理解为:反射的外部异常堆栈深度为6
)
其中
e.getCause().printStackTrace();
输入如下(这种输出方式我比较喜欢):
java.lang.RuntimeException: tdtd
at cn.sh.flyhyp.cherry.InterceptorExecutorRun$Test1.abc(InterceptorExecutorRun.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at cn.sh.flyhyp.cherry.InterceptorExecutorRun.test3(InterceptorExecutorRun.java:63)
at cn.sh.flyhyp.cherry.InterceptorExecutorRun.main(InterceptorExecutorRun.java:74)
今天研究到这里,感觉已经有点收获了,有一点疑问是,为什么jvm选择默认用第一种方式输出,有什么好处。哪位达人有更高的造诣的话,不吝赐教。
本文通过具体示例探讨了Java反射机制中异常的两种不同输出形式,并对比分析了这两种输出方式的区别,旨在帮助读者更好地理解和处理Java反射机制中的异常。
1022

被折叠的 条评论
为什么被折叠?



