Closures in Java

November 4th, 2006

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 class StateModifier extends Object
{
protected String x ;

    public StateModifier () {
x = "foo";
}

    public Thread getThread(){
final String y = "yy";

Thread t = new Thread(){
            public void run(){
x = "boo" + y;
}
};

return t;
}

    public static void main(String[] args) {
StateModifier sm = new StateModifier();
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);
}
}

Programming | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
You can keep track of new comments to this post with the comments feed.

Recent Posts

Blogroll

Siti amici

Misc

Recent Comments

Categories

Enrico Franchi graduated in Maths and Computer Science and is now studying for a Computet Science MSc (though because of italian bureaucracy that very course is to be cancelled).

RiK0's Tech Temple is using WP-Gravatar