在c#中我们有调用者信息
public void DoProcessing()
{
TraceMessage("Something happened.");
}
public void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
System.Diagnostics.Trace.WriteLine("message: " + message);
System.Diagnostics.Trace.WriteLine("member name: " + memberName);
System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}
// Sample Output:
// message: Something happened.
// member name: DoProcessing
// source file path: c:UsersusernameDocumentsVisual Studio 2012ProjectsCallerInfoCSCallerInfoCSForm1.cs
// source line number: 31
MSDN Link: CallerInfo
我想知道Java是否有等价的注释?
这些特性可以帮助我们更好地跟踪
更新:
我写了一个类:
public class Trace {
public static void trace() {
StackTraceElement[] stk = Thread.currentThread().getStackTrace();
System.out.println(String.format("LineNumber : %s, ClassName : %s, MethodName : %s, SourceLocation : %s",
stk[1].getLineNumber(), stk[1].getClassName(), stk[1].getMethodName(), stk[1].getFileName())
);
}
}
和Call trace()方法:
public class Main {
public static void main(String[] args) throws Exception {
Trace.trace();
}
}
和RESULT:
LineNumber : 8, ClassName : Trace, MethodName : trace, SourceLocation : Trace.java
这对我来说不是真的,我想要这样的结果:
LineNumber : 3, ClassName : Main, MethodName : main, SourceLocation : Main.java
实际上我现在想知道类和方法如何调用trace() (The Parent)
创建一个异常并打印它的stacktrace。
Exception e = new Exception();
e.printStackTrace();
//or
StackTraceElement[] stack = e.getStackTrace();
StackTraceElement last = stack[0];
编辑:在评论中Fabian提供了一个更好的解决方案,您不需要创建异常:
Thread.currentThread().getStackTrace()