StackTraceElement Gets a detailed instance of method call stack information

  • 2021-01-18 06:25:16
  • OfStack

This paper mainly studies StackTraceElement to obtain method call stack information related content, detailed introduction and examples are as follows.

1. What is StackTrace

The StackTrace(stack trace) stores information about the method call stack, and the printStackTrace() commonly used in exception handling is essentially printing the stack information of the exception call.

2. StackTraceElement is introduced

StackTraceElement represents a method object in StackTrace(stack trace), and the properties include the class name, method name, file name, and number of lines to call.


public final class StackTraceElement implements java.io.Serializable {
	// Normally initialized by VM (public constructor added in 1.5) 
	private String declaringClass;
	private String methodName;
	private String fileName;
	private int  lineNumber;
}

StackTraceElement is defined as final, so as a base class of java, it is not allowed to be inherited.

There are two ways to get StackTraceElement, and both return the StackTraceElement array, which is the stack information.

1, Thread. currentThread (.) getStackTrace ()

2, new Throwable (.) getStackTrace ()

The StackTraceElement array contains the contents of StackTrace(stack trace), which can be traversed to get the call between methods, namely, the current method and its caller's method name, call line number, and so on


public class TestClass {
	public static void main(String[] args) 
	  {
		new TestClass().methodA();
	}
	private void methodA(){
		System.out.println("------ Enter the methodA----------");
		methodB();
	}
	private void methodB(){
		System.out.println("------ Enter the methodB----------");
		StackTraceElement elements[] = Thread.currentThread().getStackTrace();
		for (int i = 0; i < elements.length; i++) {
			StackTraceElement stackTraceElement=elements[i];
			String className=stackTraceElement.getClassName();
			String methodName=stackTraceElement.getMethodName();
			String fileName=stackTraceElement.getFileName();
			int lineNumber=stackTraceElement.getLineNumber();
			System.out.println("StackTraceElement The array subscript  i="+i+",fileName="
			          +fileName+",className="+className+",methodName="+methodName+",lineNumber="+lineNumber);
		}
	}
}

3. Use

1. We can encapsulate a log library. When printing the target log, we can also print out the line number of the log through this call stack, so that we can quickly locate the log output line, and do not need to search globally.


public static void d(String tag, String msg, Object... params) {
  StackTraceElement targetStackTraceElement = getTargetStackTraceElement();
  Log.d(tag, "(" + targetStackTraceElement.getFileName() + ":"
      + targetStackTraceElement.getLineNumber() + ")");
  Log.d(tag, String.format(msg, params));
}

2. If we write an SDK and expect a method to be called at a fixed location, we can also check that the method is called at the correct location when it is called.

For example, it must be executed in Activity.onResume, PVSdk.onResume, so when we call the PVSdk.onResume method, we check whether the method is called in the onResume method by getting the call stack information.


public class PVSdk {
	public static void onResume() {
		StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
		Boolean result = false;
		for (StackTraceElement stackTraceElement : stackTrace) {
			String methodName = stackTraceElement.getMethodName();
			String className = stackTraceElement.getClassName();
			try {
				Boolean assignableFromClass = Class.forName(className).isAssignableFrom(Activity.class);
				if (assignableFromClass && "onResume".equals(methodName)) {
					result = true;
					break;
				}
			}
			catch (ClassNotFoundException e) {
			}
		}
		if (!result)
		      throw new RuntimeException("PVSdk.onResume must in Activity.onResume");
	}
}

3. When we are doing source code analysis, if we want to analyze the execution process of the entire code, we can get it by printing the information of the stack, which is still very useful in source code analysis.

conclusion

This article on StackTraceElement get method call stack information instance details of all content, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: