Call stack

Call chain monitoring is not enough to simply get the order of calls, as described earlier:

Get the call stack

Get the call stack in Java as follows:

Thread.currentThread().getStackTrace()
Copy the code

Code examples:

public class Man {

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

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

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

	public void eat(a) {
		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"); }}Copy the code

Output result:

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
Copy the code

You can see that the third stack is the method that calls EAT.

Three, notes

Note in real code:

  1. It does not have to be the third stack that is the parent of the current method, as there may be other parent methods in spring calls, but the number is greater than 3.
  2. In the process of a call, some methods may be circularly called and have more than one method with the same name. Therefore, it is not always possible to find the corresponding parent method by class name and method name. Instead, we should look for the nearest method with the same name in the call chain.

end.


Wechat Official Account:


Join “Java stack actual combat camp” knowledge planet, participate in the discussion, more actual combat code to share, is not a few jins of apple, a few glory props!

t.zsxq.com/RNzfi2j