How can one tell if a local variable is 'final' from Java bytecode? (Related to BCEL)
Asked Answered
G

3

6

Where is information such as if a local variable is "final" stored in Java bytecode? I know that for fields (global variables) and methods these are found in the access flag bits, but cannot seem to find the equivalent in the local variable table.

I am interested in this question as I am using BCEL to check if a local variable is final, and have found the equivalent for fields, methods and classes in the class AccessFlags.

Thanks in advance.

Gordie answered 9/10, 2011 at 14:0 Comment(0)
E
4

The finality of local variables is checked by the compiler and doesn't make it to the bytecode. This information isn't required at runtime, and hence isn't stored in the bytecode.

The JVM treats final and non-final local variables in the same way.

Enlil answered 9/10, 2011 at 14:10 Comment(3)
I understand, but why is this not so for global variables too then please?Gordie
Because global variables can be reused in other classes and/or programs. When the compiler is compiling a class using your final variable, it needs to know thisEnlil
Thank you that makes perfect sense nowGordie
T
2

Short answer - you can't. The 'final' access flag for local variables only tells compiler that variable value can't be reassigned. See section 4.7.13 of the JVM specification.

Tertiary answered 9/10, 2011 at 14:15 Comment(0)
A
1

I don't believe you can determine the finality of a local variable; this can be proven by writing a small method with and without the final keyword and comparing the bytecode.

Albaalbacete answered 9/10, 2011 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.