Dynamically get the current line number

前端 未结 5 1977
一整个雨季
一整个雨季 2020-12-14 00:58

Is there a way in Java to dynamically get the current line number through reflection or some awesome API? Just like when exceptions occur, the line number gets printed out i

5条回答
  •  长情又很酷
    2020-12-14 01:23

    First of all: If anything, then the logging pattern (or layouter, or whatever your logging framework calls that part) should do this. The logger call in your code should only write the actual business information. Information about the where should be added by the logger.

    Next: getting that kind of operation is expensive (in terms of time), because Java is not optimized for this. At runtime, the JVM need to inspect its state, load/parse debug information and find the line number corresponding to a given instruction. That's why this kind of information is usually just given when an exception occurs (in which case we already have a problem and know that the time spent will usually be worth it).

    And last but not least: if for some reason you need that information on your own, you can use Thread.getStackTrace() and inspect the second StackTraceElement on it.

提交回复
热议问题