We all know you can't do things like this:
int a = 7;
new Runnable() {
public void run() {
System.out.println(a);
}
}.run();
...
...without making a
final. I get the technical reason why and it's because local variables live on the stack and you can't safely make a copy unless you know it won't change.
What I struggle to see however is why the compiler doesn't have an implementation hack so that it when it sees the above situation it compiles down to something like:
int[] a = {7};
new Runnable() {
public void run() {
System.out.println(a[0]);
}
}.run();
...
Then we're in the position where it's safe to access a from an anonymous inner class and indeed change it if we wish. Of course, it might only do this hack when we actually change a
. As far as I could see this would be a relatively simple thing to put in, would work for all types and would allow a
to be changed from whatever context. Of course, the above proposal could be changed to use synthetic wrapper classes for multiple values or another approach that's a bit more efficient, but the idea is the same. I guess there's a small performance hit, but I doubt it'd be excessive especially with the potential for more optimisations under the hood. Aside from perhaps certain reflective calls that rely on synthetic fields being a certain way breaking, I can't see many disadvantages, but I've never heard it seriously proposed! Is there a reason why?