Saturday, November 4, 2006

Closures in Java

This is a hint abount implementing closures in Java. Of course, if you want to do it in an acceptable way, you would create a custom interface that Does The Right Thing™, something like (semi pseudocode)
interface Closure {
    public Object foo(Object bar);
}
However, you can get some ideas from the sequent code

public classStateModifierextendsObject{
    protectedString x ;
    
    public StateModifier() {
        x = "foo";
    }
    
    public ThreadgetThread() {
        finalString y = "yy";
        Thread t = newThread() {
            public voidrun(){
                x = "boo"+ y;
            }
        };
        return t;
    }
    
    public static voidmain(String[] args) {
        StateModifier sm = newStateModifier();
        Thread t1 = sm.getThread();
        System.out.println(sm.x);
        t1.start();
        try {
            t1.join();
        } catch (Exception e){
            // ...
        }
        System.out.println(sm.x);
        System.exit(0);
    }
}

No comments: