Posts Tagged ‘closure’

Closure in Java

Monday, April 20th, 2009

I believe Closure should be part of any modern language, so I was delighted to read about Closure for Java (currently a JSR draft I believe) from here. Currently, Closure is not implemented in Java and is impossible to implement in its natural form. We can attempt to implement closures using anonymous objects, but that comes with two main issue: (1) it can not access non-final variables defined in its enclosing code; (2) you have to define closure interface for every possible scenario. We really can’t do anything with the first problem; but, as we see later, we can simplify the syntax considerably. Here is an example:

public interface ClosureIntReturnInt {
  public int invoke(int arg1);

public void testNaiveClosure() {
  final int a = 1; // This must be final!
  ClosureIntReturnInt addA =
      new ClosureIntReturnInt() {
    public int invoke(int v) {
      return v + a;

  assertEquals(3, addA.invoke(2));

This is obviously not a very good solution. So my first instinct would be to genericize the closure interface. Sure enough, it simplifies the problem by quite a bit. Here is my genericize Closure interface:

public interface Closure0Arg<R> {
  public R invoke();
public interface Closure1Arg<R, A1> {
  public R invoke(A1 arg1);
public interface Closure2Args<R, A1, A2> {
  public R invoke(A1 arg1, A2 arg2);

Sure enough, this works fine and it becomes much easier to use. It is of course still inconvenient for people who came from functional programming world. The problem is: (1) there is no universal Closure, that means you have to keep track of the Closure type as type annotation, many, including me would love to ditch the cumbersome type annotation; (2) you have to write the interface for each number of arguments (much better than writing for each argument type of course, but still…).

Of course, OTOH, this is the best you can do while maintaining static checking ability. Here is an example usage:

public void testClosure1Arg() {
  Closure1Arg intToString =
      new Closure1Arg<String, Integer>() {
    public String invoke(Integer v) {
      return v.toString();

  assertEquals("5", intToString.invoke(5));

A sharp reader would have noticed several (not-very-correct?) things happening here. First, we eliminate the generic from intToString type annotation. This does not change the semantics of the code and make the code looks cleaner; however, it does create an “unchecked” warning with the Java compiler. Secondly, we utilize autoboxing freely in this implementation. Since we are utilizing generics, R, A1, …, An must all be objects. This is obviously undesirable and ugly. However, due to autoboxing, this is no longer an issue (except performance-wise).

So far, this is really the best we can do while preserving static type checking. However, if we ignore additional security provided by static type checking, we can go a step further: we can introduce a Closure base class; the rest of the closures interface (Closure1Arg, etc.) will become an abstract class that extends the Closure class. This is where all the interesting stuffs are happening. Here is the source code for the Closure class.

public class Closure<R> {
  public R invoke(Object... args) {
    Class[] classes = new Class[args.length];
    // This is okay since generic type annotation
    // is stripped after compilation. We only
    // need to find invoke method with
    // the right number of params.
    Arrays.fill(classes, Object.class);

    try {
      // Search for correct invoke method
      // and execute it.
      Method method =
              "invoke", classes);
      return (R) method.invoke(this, args);
    } catch (Exception e) {
      // TODO: handle exceptions correctly.
      // ClosureException is a runtime exception.
      throw new ClosureException("Error", e);

// e.g. of ClosureNArg abstract class.
public abstract class Closure1Arg<R, A1>
    extends Closure<R> {
  public abstract R invoke(A1 arg);

This code completely sacrifices static checking. Now we can simply have each closures to be stored in variables of Closure type. When invoke is called, the method from the base class (above) is called. It will find the correct (i.e. more specialized) invoke method (declared in the concrete anonymous object derived from the subclass) to call based on the type of the arguments to invoke. Here is how we can use it:

public void testClosure1() {
  Closure<Integer> addOne =
      new Closure1Arg<Integer, Integer>() {
    public Integer invoke(Integer arg) {
      return arg + 1;
  assertEquals(3, (int) addOne.invoke(2));

public void testClosure2() {
  Closure<Double> add =
      new Closure2Args<Double, Double, Double>() {
    public Double invoke(Double a, Double b) {
      return a + b;
  assertEquals(7.5, add.invoke(4.2, 3.3));

Sweet! Now this is neat! Of course, we have ignored much of the static checking and replace them with dynamic, runtime checking. I have removed much of the exception checking code in Closure<R> base class to save space and focus on the meat. Again, I’d draw readers’ attention to several important code fragments:

  1. We catch most of the checked exception and replaced them with unchecked runtime exception to make the usage much cleaner, this follows more closely to dynamic, interpreted language rather than static language (as with Java);
  2. We readily suppress warning with @SuppressWarnings (heh!);
  3. The code, arguably, takes a bit of performance hit, so users who are more concerned about performance should probably not use this (squeezing performance usually means messier code; closure is for elegance, not mess);
  4. You may want to write simple script to autogenerate ClosureNArgs (N from 0 to however many arguments you think is reasonable; I personally generate up to 7 arguments);
  5. You probably want to generate closures for void return value as well; that would make things messier (much messier) though. It is probably easier to return null instead.
  6. Here, I opt to go for clean ClosureNArgs subclasses. Others may opt to add some ugliness to the subclasses and make the base class cleaner (and likely result in faster closure code). I will likely experiment with this further, and try to implement variable binding as well.

I found it very interesting to implement Closure in Java; hope you do too. :)

EDIT: This is interesting, wonder how I missed this earlier: Closures for the Java Programming Language (v0.5).

EDIT 2: I simplified Closure&ltR> a little bit more. The simplification is a result of stripping of the generic type annotation after compilation. So the base class need only hunt for invoke method with the right number of parameters.