'How to get line number of an instance variable from a java object during runtime

I want to find line number of an instance variable in Java file during run time. So far my understanding, it can be done through java reflection but don't know how to do it.

Thanks in advance



Solution 1:[1]

Short answer: no cannot be done.

If you want to get any kind of line number information at runtime, you first of all have to be sure that your classes have been compiled retaining line number information. If you do not own those class files, then this is not guaranteed.

Secondly, it is not clear what you want: the line number of a variable declaration or the initialization of the variable, or another assignment to the variable. If it were the declaration (without an assignment), then there is not line information retained for that regardless (I think -- try placing a debug breakpoint on a variable declaration that does not have an assignment to it and you will understand). The other two possibilities you could observe in a debugger with breakpoints, but there would be no way to capture a particular statement programatically.

Finally, the runtime will show line numbers in stacktraces, but obviously only if you force the throw of an exception or use Thread.currentThread().getStackTrace(), which means you would have to access and modify the code for each possible line number you wanted to test.

I suppose this might be made a tiny bit easier with some custom annotation that would (using aspect programming) that would insert code to output line numbers wherever the annotation appeared, but you would still have to annotate any line you were interested in.

Reflection will not give you line numbers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1