__LINE__ equivalent in Java?

Steve Schnepp picture Steve Schnepp · Aug 28, 2009 · Viewed 11.8k times · Source

I'm searching a way to include __LINE__ as a compile-time constant in outputted messages.

Various solutions seem to exist, but with a big runtime penalty as suggested in __LINE__ in JS and __LINE__ in C#. They are usually always based upon a runtime object StackFrame as log4j.

Using the log4j possibility of enabling/disabling on a needed basis isn't an option either since usually when an error happens, it's too late to enable the line numbers, and inlined code doesn't seem to have any line numbers any more. . Would it be possible to either :

  1. Pre-process the java source files before compilation, ideally with something integrated with Eclipse1, so the it can be tested on the developpement platform also.
  2. Be able to pre-process the class at loading time. The overhead would then be negligible by being amortized.

1. Actually I do use an ugly hack: calling a custom preprocessor just after checkout on the build server via ANT tricks

Answer

ZZ Coder picture ZZ Coder · Aug 28, 2009

It's impossible to get the effect of __LINE__ in C which happens at compile time.

You can get line number by calling a function like this at runtime,

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