Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 327
ET13 Avatar asked Oct 09 '11 14:10

ET13


People also ask

Can we define local variable as final in Java?

final is the only allowed access modifier for local variables. final local variable is not required to be initialized during declaration. final local variable allows compiler to generate an optimized code. final local variable can be used by anonymous inner class or in anonymous methods.

Is bytecode generated after Java code has been interpreted?

Java source code is first compiled to bytecode, and subsequently interpreted or executed as native code.


3 Answers

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.

like image 121
Vivien Barousse Avatar answered Oct 04 '22 22:10

Vivien Barousse


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.

like image 25
Eugene Kuleshov Avatar answered Oct 05 '22 00:10

Eugene Kuleshov


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.

like image 44
Dave Newton Avatar answered Oct 04 '22 23:10

Dave Newton