The correct use of the thread call stack to get the name of a higher level function calls

Using Thread.currentThread () getStackTrace () [1] .getMethodName () function to get the current name no problem, my problem is the need to get the name of the two function calls, roughly like this code:

public class A {
    protected final String getId() {
        //返回[类名.函数名]字符串代码
        Thread.currentThread().getStackTrace()[3].getMethodName();
    }
    protected final <T> T getXXX() {
        return otherCall(getId());
    }
}
public class B extends A{
    public myClass myCall(){
        return getXXX();
    }

According to my idea, StackTrace 0 is GetStackTrace, 1 is getId, 2 is getXXX, 3 is myCall, so return myCall function name should be used 3, the results of it, after running return getXXX, hit the call stack and saw what I expected is not the same, more getXXX several functions with the same name, on second thought, I used the spring, with the development environment and the jrebel, the two most favorite thing is secretly help you generate dynamic proxy class in the background, it is estimated the problem is here, no way, had made a filtering code:

private final String getId() {
		StackTraceElement[] se = Thread.currentThread().getStackTrace();
		//堆栈的第0个为"getStackTrace"函数,第1个为本函数
		String s = se[1].getMethodName();
		//第二个非"getId"同名函数为本类调用"getId"的其他函数,第三个才是子类调用本类模板函数的真正函数
		for(int i = 2, n = se.length, count = 0; i < n; ++i) {
			String v = se[i].getMethodName();
			if(s.equals(v)) continue;
			s = v;
			//第一次匹配是本类的其他函数,第二次匹配才是子类的调用函数
			if(++count >= 2) break;
		}
		return getClass().getSimpleName() + "." + s;
	}

Compile, run, ha ha, this one right, and leave a mark, hoping to help other people experiencing the same problem.

Reproduced in: https: //my.oschina.net/kivensoft/blog/549366

Guess you like

Origin blog.csdn.net/weixin_34279579/article/details/92058661