简体   繁体   中英

Caller Information in Java

In C# we have Caller Information

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

I want to know Java has equivalent annotations or not ?

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 :

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)

You create an exception and print it's 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:

Thread.currentThread().getStackTrace()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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