what am i missing here. array length -1 is the top element in the stack. the method that called the top stack element should be arraylength -2 , so why is this not validating ?
in the code gym solution they used [2] for everything. That doesnt make much sense to me. if there are like 5 method that calls each others, how does the [2] used for all the methods gets the method's caller Name???
public class Solution {
public static void main(String[] args) {
method1();
}
public static String method1() {
method2();
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
public static String method2() {
method3();
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
package en.codegym.task.jdk13.task09.task0902;
/*
Stack trace revisited
*/
public class Solution {
public static void main(String[] args) {
method1();
}
public static String method1() {
method2();
//write your code here
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
return elements[elements.length -2].getMethodName() ;
}
public static String method2() {
method3();
//write your code here
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
return elements[elements.length -2].getMethodName();
}
public static String method3() {
method4();
//write your code here
StackTraceElement[] elements= Thread.currentThread().getStackTrace();
return elements[elements.length-2].getMethodName();
}
public static String method4() {
method5();
//write your code here
StackTraceElement[] elements = Thread.currentThread().getStackTrace() ;
return elements[elements.length -2].getMethodName();
}
public static String method5() {
//write your code here
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
return elements[elements.length-2].getMethodName();
}
}