What is the significance of referencing the number 2 in the index. My thinking would be that it wants to reference the previous stack so surely it should be a 1 because we start counting from zero?
Daniel Whyte
Level 17
Thread.currentThread().getStackTrace()[2]
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Karas Java Developer
2 March 2021, 18:05
Less words, basically stack trace being an array, the 2 as commented below will pull who called it.
It has to be the same in all, otherwise you will call other parts of the array but you want the 2 who called it.
+1
Nouser
2 March 2021, 14:23useful
getStackTrace()
Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.
Means the last element, the zeroth one, is getStackTrace, the first is the method in which getStackTrace has been called and the 2nd, of course the method that called the first ste element.
Place that in mthod5 and check the output
+3
CaseyMacy
6 April 2022, 00:48
This makes sense. Before your explanation, this seemed arbitrary. Thanks for bringing meaning to it; I will be more likely to remember it now
0