Good day. Help me understand the essence of StackTrace.
The study material explains
The java machine records all function calls. She has a special collection for this - the stack. When one function calls another, the Java machine pushes a new StackTraceElement into this stack. When the function ends, this item is removed from the stack. Thus, this stack always keeps up-to-date information about the current state of the “function call stack”
The following is an example.
public static void main(String[] args) { method1(); } public static void method1() { method2(); } public static void method2() { method3(); } public static void method3() { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); for (StackTraceElement element : stackTraceElements) { System.out.println(element.getMethodName()); } } As a result of which we get
getStackTrace method3 method2 method1 main If I understand everything correctly, then the design
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); works as follows:
//Cоздаём переменную типа StackTraceElement[] StackTraceElement[] stackTraceElements //Присваеваем ей ссылку на текущий поток и заносим в массив специальные элементы StackTrace Thread.currentThread().getStackTrace() Question number 1: how in this array StackTraceElement[] all the information about the called methods, if it is said that after executing the method information from the stack is removed?
Question number 2: In one of the tasks asked to return the name of the method that calls it
public static void main(String[] args) throws Exception { method1(); } public static String method1() { method2(); return Thread.currentThread().getStackTrace()[2].getMethodName(); } public static String method2() { method3(); return Thread.currentThread().getStackTrace()[2].getMethodName(); } public static String method3() { method4(); return Thread.currentThread().getStackTrace()[2].getMethodName(); } public static String method4() { method5(); return Thread.currentThread().getStackTrace()[2].getMethodName(); } public static String method5() { return Thread.currentThread().getStackTrace()[2].getMethodName(); } How does the design work
return Thread.currentThread().getStackTrace()[2].getMethodName(); if we did not create a StackTraceElement[] . Does this mean that it is implicitly created by the JVM during program execution?