我需要一个建议
class A{
B b;
}
Class B{
P String something();
}
Run Code Online (Sandbox Code Playgroud)
在
class test{
B b = new B();
b.something();
}
something()
Run Code Online (Sandbox Code Playgroud)
必须返回cal-lee类的名称,如果有人叫我(按名字)我应该知道他的名字.
解决方案是以编程方式生成堆栈跟踪:
private static String getCallerName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals("B") && ste.getClassName().indexOf("java.lang.Thread")!=0) {
return ste.getClassName();
// you could also use ste.getMethodName() or ste.getLineNumber()
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
你会像这样使用它,例如:
public void something() {
System.out.println("called by " + getCallerName());
}
Run Code Online (Sandbox Code Playgroud)