So Jav allows you to have anonymous inner classes. For example this is a
really easy (if ugly) way to run something asynchronously
new Thread(new Runnable() {
public void run() {
// do some stuff
}
}).start();
All well and good. But there is one down side. Say you want to, let's
say, increment a counter;
int counter = 0;
new Thread(new Runnable() {
public void run() {
counter++;
}
}).start();
Perfectly reasonable, right?
BZZZZZZZZZZZZZZZZZZZT! Wrong!
You can't access anything other than final variables from within an
anonymous class.
Which means that
final int counter = 0;
new Thread(new Runnable() {
public void run() {
counter++;
}
}).start();
doesn't work because, well, counter is final.
So how do you get around this?
final int[] counter = { 0 };
new Thread(new Runnable() {
public void run() {
counter[0]++;
}
}).start();
I mean. Seriously. What The Fuck?
Of course this gets extra special fun if you want to do something with
exceptions.
Let's say you want to do
try {
final Foo foo = FooFactory.getFoo();
Bar.doSomething(new BarRunner() {
public void quux() {
foo.execute();
}
});
} catch (SomeCommonException e) {
System.err.println("Got an exception: "+e);
} finally {
FooFactory.release(foo);
}
Well you can't because the finally clause won't see the foo object but
you can't do
final Foo foo;
try {
foo = FooFactory.getFoo();
Bar.doSomething(new BarRunner() {
public void quux() {
foo.execute();
}
});
} catch (SomeCommonException e) {
System.err.println("Got an exception: "+e);
} finally {
FooFactory.release(foo);
}
because that doesn't make sense. So what you have to do is
Foo foo;
try {
foo = FooFactory.getFoo();
runBar(foo);
} catch (SomeCommonException e) {
System.err.println("Got an exception: "+e);
} finally {
FooFactory.release(foo);
}
public void runBar(final Foo foo) {
Bar.doSomething(new BarRunner() {
public void quux() {
foo.execute();
}
});
}
And people wonder why Java has a reputation as being verbose?
*sigh*