java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java StackTraceElement

Java StackTraceElement实例代码

作者:司马懿字仲达

这篇文章主要介绍了Java StackTraceElement实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下

本文研究的主要是Java StackTraceElement的相关内容,具体介绍如下。

实例:

package com.demo.test;
public class StackTraceDemo {
	public static void testA() {
		testB();
	}
	public static void testB() {
		StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
		System.out.println("-------> StackTraceElement[]");
		for (int i = 0; i < stackTraceElements.length; i++) {
			System.out.println("-------> " + i);
			System.out.println(stackTraceElements[i]);
			System.out.println("StackTraceElement.getClassName() => " + stackTraceElements[i].getClassName());
			System.out.println("StackTraceElement.getFileName() => " + stackTraceElements[i].getFileName());
			System.out.println("StackTraceElement.getLineNumber() => " + stackTraceElements[i].getLineNumber());
			System.out.println("StackTraceElement.getMethodName() => " + stackTraceElements[i].getMethodName());
			System.out.println("StackTraceElement.isNativeMethod() => " + stackTraceElements[i].isNativeMethod());
		}
	}
	public static String getMethodName() {
		StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
		if(stackTraceElements.length > 2) {
			return stackTraceElements[2].getMethodName();
		}
		return null;
	}
	public static void main(String[] args) {
		testA();
		System.out.println("\nthis's method name is " + getMethodName());
	}
}

输出:

-------> StackTraceElement[]
-------> 0
java.lang.Thread.getStackTrace(Unknown Source)
StackTraceElement.getClassName() => java.lang.Thread
StackTraceElement.getFileName() => null
StackTraceElement.getLineNumber() => -1
StackTraceElement.getMethodName() => getStackTrace
StackTraceElement.isNativeMethod() => false
-------> 1
com.demo.test.StackTraceDemo.testB(StackTraceDemo.java:10)
StackTraceElement.getClassName() => com.demo.test.StackTraceDemo
StackTraceElement.getFileName() => StackTraceDemo.java
StackTraceElement.getLineNumber() => 10
StackTraceElement.getMethodName() => testB
StackTraceElement.isNativeMethod() => false
-------> 2
com.demo.test.StackTraceDemo.testA(StackTraceDemo.java:6)
StackTraceElement.getClassName() => com.demo.test.StackTraceDemo
StackTraceElement.getFileName() => StackTraceDemo.java
StackTraceElement.getLineNumber() => 6
StackTraceElement.getMethodName() => testA
StackTraceElement.isNativeMethod() => false
-------> 3
com.demo.test.StackTraceDemo.main(StackTraceDemo.java:32)
StackTraceElement.getClassName() => com.demo.test.StackTraceDemo
StackTraceElement.getFileName() => StackTraceDemo.java
StackTraceElement.getLineNumber() => 32
StackTraceElement.getMethodName() => main
StackTraceElement.isNativeMethod() => false

this's method name is main

总结

以上就是本文关于Java StackTraceElement实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

您可能感兴趣的文章:
阅读全文