1Dec/093
Replacing conventional loops with Closures in Java 6
A useful way to promote a low-level code reuse is to use Closures. Think of it as writing generic functions that can be passed around in method calls.
Here's a code snippet that replaces a loop with a Closure:
Closure buildNode = new Closure() {
//do processing in execute method
public void execute(final Object obj) {
nodes = new ArrayList();
NodeBuilderType builderType = (NodeBuilderType) obj;
NodeBuilderStrategy strategy = strategies.get(builderType
.getClass());
if (strategy == null) {
throw new NodeBuilderException(
"No strategy found for Node type:" + builderType);
}
nodes.add(strategy.build(builderType, document));
}
};
//runs a 'for' closure
ClosureUtils.forClosure(builderTypes.size(), buildNode);
Commons Collections also provides utility classes which allows for Closures to be very useful for Collections processing. Here's one that applies a Closure on a Collection:
//define your closure
Closure appendChild = new Closure() {
//do processing in execute method
public void execute(final Object obj) {
Node child = (Node) obj;
usageAttr.appendChild(child);
}
};
//executes appendChild against nodes
CollectionUtils.forAllDo(nodes, appendChild);
For more information, look at Apache's Commons Collections. Credit goes to Chris Shayan for sharing this a few weeks back. Update: I'll have to say that this way of achieving closures in JDK<7 is a hack, and feels like a hack but it's one of the solutions available. I'm still eagerly waiting for JDK to allow a more 'native' closure.