Java call key chain tracking technology (V) to obtain the call stack

First, the call stack

Monitoring the call chain simply is not enough to obtain the calling sequence, as previously described:

Left only reflects the order of the right order and reflects the call stack information.

Second, get the call stack

Gets the call stack in Java as follows:

Thread.currentThread().getStackTrace()
复制代码

Code Example:

public class Man {

	public static void main(String[] args) {
		Man man = new Man();
		man.getup();
		man.brushTeeth();
		man.eat();
	}

	public void getup() {
		System.out.println("getup");
	}

	public void brushTeeth() {
		System.out.println("brush teeth");
	}

	public void eat() {
		StackTraceElement[] elements = Thread.currentThread().getStackTrace();
		for (int i = 0; i < elements.length; i++) {
			StringBuffer buffer = new StringBuffer();
			buffer.append("index: ").append(i).append(" ClassName: ").append(elements[i].getClassName())
					.append(" Method Name : " + elements[i].getMethodName());
			System.out.println(buffer.toString());
		}
		System.out.println("eat");
	}
}
复制代码

Output:

getup
brush teeth
index: 0 ClassName: java.lang.Thread Method Name : getStackTrace
index: 1 ClassName: com.javashizhan.demo.Man Method Name : eat
index: 2 ClassName: com.javashizhan.demo.Man Method Name : main
eat
复制代码

We can see the first three of the stack is a method call eat.

Third, pay attention

Note that in the actual code:

  1. Not necessarily a third stack is the father of the current method of method, such as calling in the spring there will be other parent method, this number is greater than 3.
  2. One call during some methods may be calling the cycle leading to multiple methods of the same name, so by the class and method names are not necessarily accurate method to find the corresponding parent should look for the same name as a method on a recent call chain.

end.


Micro-channel public number:


Adding "Java stack combat battalion" knowledge planet, participate in discussions, share the code more practical, not that several kilograms of apples, a few props glory do for you!

t.zsxq.com/RNzfi2j

Guess you like

Origin juejin.im/post/5d48562b518825673a6ae37f