Eclipse: "println(__LINE__);" -- does such a preprocessor macro exist to programmatically get the code's Line Number?

StackOverflow https://stackoverflow.com/questions/22677815

Question

Note: To be clear, the question being asked is not about "How can I display line numbers in Eclipse?" That is answered here @ StackOverflow.

Goal: I want to know if Eclipse has a macro that acts as getLineNumber() the same way Visual Studio has the ability to use the preprocessor macro __LINE__ to easily/universally get the line# for where this particular call to getLineNumber() lives on. It's useful for knowing if a line of code was hit, without using a debugger/breakpoints.

I'd like to debug using: println("I just hit file@line: "+__FILE__ +'@'+ __LINE__ );

I am seeking a universal macro that can be copied and pasted to any file/any line, so that those values are known at/before compile time. Does Java/Eclipse offer such a feature? Possibly in an Eclipse plugin?

I can't find any info on this anywhere, I'm at a loss. Thanks.

Was it helpful?

Solution

You can try that:

System.out.println("I just hit file@line: "+Thread.currentThread().getStackTrace()[1].getFileName() +'@'+ Thread.currentThread().getStackTrace()[1].getLineNumber());

Thread.currentThread().getStackTrace() will return an array of StackTraceElement, and we take the second element (the first one will be in the Thread class), and get the file name and line number from that.

EDIT: You may also want to create a static function (you can put it in an utilitary class) to do that (which will avoid the problems with the different java implementations):

public static void printCurrentFileAndLine() {
    final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
    for (int i=0; i<ste.length; i++)
        if (ste[i].getMethodName().equals("printCurrentFileAndLine")) {
            System.out.println("I just hit file@line: "+ste[i+1].getFileName() +'@'+ ste[i+1].getLineNumber() );
            break;
        }
}

And you just need to call:

printCurrentFileAndLine();

OTHER TIPS

Be careful with Thread.getStackTrace() method, it's a costly method. Just use it when you really need.

For more information about that: How Expensive is Thread.getStackTrace()?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top