2

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

2
  • 1
    What is the use case you want to fulfil? Maybe, there is another way to solve this. Commented Nov 6, 2013 at 22:29
  • 4
    Voted to reopen, because: 1. This question asks about the line number of a field, not the line number of a method; 2. the answers about obtaining the line number of a method cannot be applied to obtaining the line number of a field. Specifically, javassist.FieldInfo does not contain a getLineNumber() method as javassist.MethodInfo does, so it appears to be impossible to get the line number of a field using javassist. Commented Jul 26, 2014 at 15:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.