简体   繁体   English

Java中的呼叫者信息

[英]Caller Information in Java

In C# we have Caller Information 在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:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
//  source line number: 31

MSDN Link : CallerInfo MSDN链接: CallerInfo

I want to know Java has equivalent annotations or not ? 我想知道Java是否具有等效的注释?

these features can help us for better tracing 这些功能可以帮助我们更好地跟踪

UPDATE : 更新:

I wrote a class : 我写了一堂课:

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())


        );
    }

}

and Call trace() method : 和调用trace()方法:

public class Main {
    public static void main(String[] args) throws Exception {
        Trace.trace();
    }
}

and RESULT : 和结果:

LineNumber : 8, ClassName : Trace, MethodName : trace, SourceLocation : Trace.java

it is not true for me I want a result like this : 对我来说这不是真的,我想要这样的结果:

LineNumber : 3, ClassName : Main, MethodName : main, SourceLocation : Main.java

In fact I want to now how class and method call my trace() (The Parent) 实际上,我现在想知道类和方法如何调用我的trace()(父类)

You create an exception and print it's stacktrace. 您创建一个异常并打印它的stacktrace。

Exception e = new Exception();
e.printStackTrace();
//or
StackTraceElement[] stack = e.getStackTrace();
StackTraceElement last = stack[0];

EDIT: In the comments Fabian provided a better solution, you don't need to create an exception: 编辑:在Fabian提供了更好的解决方案的注释中,您不需要创建异常:

Thread.currentThread().getStackTrace()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM