I think your solution is the simplest way.
Another option would be to refactor the creation of the inner class into a factory function that does it for you, then your loop itself could be something clean like:
List<Runnable> r = new ArrayList<>();
for(int i = 0; i < 10; i++) {
r.add(generateRunnablePrinter(i));
}
And the factory function could just declare a final parameter:
private Runnable generateRunnablePrinter(final int value) {
return new Runnable() {
public void run() {
System.out.println(value);
}
};
}
I prefer this refactored approach because it keeps the code cleaner, is relatively self descriptive and also hides away all the inner class plumbing.
Random digression: if you consider anonymous inner classes to be equivalent to closures, then generateRunnablePrinter
is effectively a higher order function. Who said you can't do functional programming in Java :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…