Tuesday, 21 September 2010

How final is final?

One interesting tidbit from Spiff development. How final is
final int x = 1
? Answer: Not very, if you're using reflection. Field.setAccessible(true) will soon get you round any awkward encapsulation issues.

So, newly armed with that knowledge, what's printed out here?
public class HowFinal {
private final int x = 1;

public static void main(String[] args) throws Exception {
HowFinal howFinal = new HowFinal();
Field f = howFinal.getClass().getDeclaredField("x");

public int getX() {
return x;

The answer, unexpectedly, is

Er, so x was final after all? Sort of. The compiler inlines constants at compile time, so as far as the runtime JVM is concerned, getX() contains the code return 1;. Querying the field via reflection shows it's true value of 2.

Is there any question whose answer doesn't start with "it depends"?

No comments: