What does .getStackTrace()[2] do?
Why there is a number "2" in it?
What does .getStackTrace()[2] do?
Dyskutowane
Komentarze (3)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Thomas
26 listopada 2021, 12:28
No idea what [2] may mean? Array eventually? If that is true you could try to explore what that array contains. I'm nearly sure that this will explain your question.
0
Szczepan Z.
26 listopada 2021, 13:22
Complete code:
package pl.codegym.task.task09.task0903;
/*
Kto mnie wywołał?
*/
public class Solution {
public static void main(String[] args) throws Exception {
method1();
}
public static int method1() {
method2();
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method2() {
method3();
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method3() {
method4();
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method4() {
method5();
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method5() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
}
0
Thomas
26 listopada 2021, 14:10
Yes, the stack trace is like a call history of methods. Change method5 to
that's what you're probably supposed to do. Examining what's happening. Now you see that the stacktrace shows all methods from main to method5 and the last called method, getStackTrace. Now when you want to return from a method the caller is known by the jvm.
So the first element (index 0) is the call to getStacktrace, the method calling getStacktrace is index 1 and the method that called this method is saved in index 2... easy ;) 0