-1

I am trying to print the current line number(line number of ide) of a certain code from intellij. How do I do that?

1 System.out.print(getCurrentLineNo());//sample code
2 System.out.print(getCurrentLineNo());//sample code
3 System.out.print(getCurrentLineNo());//sample code
4 System.out.print(getCurrentLineNo());//sample code
AyukNayr
  • 386
  • 2
  • 21

3 Answers3

3

One way to do this is to get the stack trace element and call getLineNumber.

public static int getCurrentLineNumber() {
    return Thread.currentThread().getStackTrace()[2].getLineNumber();
}

Note that I used an index of 2 because that refers to the frame of the method that calls getCurrentLineNumber. If you are just doing this inline, i.e. like this:

System.out.println(Thread.currentThread().getStackTrace()[1].getLineNumber());

You should use an index of 1 instead.

Note that an index of 0 refers to the frame of the getStackTrace method.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

I suppose it too expensive to get StatckTrace for that, but it can help you for some debug.

System.out.println(new Exception().getStackTrace()[0].getLineNumber());

Also, you can look here

Dred
  • 1,076
  • 8
  • 24
1

You can get line number like this...

public static int getCurrentLineNo() {
        return Thread.currentThread().getStackTrace()[2].getLineNumber();
    }
Rowi
  • 545
  • 3
  • 9