views:

232

answers:

4

In C#, you can define small pieces of code called delegates anonymously (even though they are nothing more than syntactic sugar). So, or example, I can do this:

public string DoSomething(Func<string, string> someDelegate)
{
     // Do something involving someDelegate(string s)
} 

DoSomething(delegate(string s){ return s += "asd"; });
DoSomething(delegate(string s){ return s.Reverse(); });

Is it possible to pass code like this in Java? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics).

+5  A: 

Not exactly like this but Java has something similar.

It's called anonymous inner classes.

Let me give you an example:

DoSomething(new Runnable() {
   public void run() {
       // "delegate" body
   }
});

It's a little more verbose and requires an interface to implement, but other than that it's pretty much the same thing

Gregory Mostizky
You need to add `public void run() { ... }` around your `// "delegate" body` (since it's an anonymous inner class, not an anonymous method).
Chris Boyle
Ooops :) Thanks, fixing this now.
Gregory Mostizky
+7  A: 

The closest Java has to delegates are single method interfaces. You could use an anonymous inner class.

interface StringFunc {
   String func(String s);
}

void doSomething(StringFunc funk) {
   System.out.println(funk.func("whatever"));
}

doSomething(new StringFunc() {
      public String func(String s) {
           return s + "asd";
      }
   });


doSomething(new StringFunc() {
      public String func(String s) {
           return new StringBuffer(s).reverse().toString();
      }
   });
mlk
[Google Collections][1] and Groovy[2] might be of interest to you.[1] http://code.google.com/p/google-collections/[2] http://groovy.codehaus.org/
mlk
Sorry about taking so long to accept the answer - the accept button is broken in Chrome.
Callum Rogers
+1  A: 

Is it possible to pass code like this in Java? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics).

Since the question asked about the Processing-specific answer, there is no direct equivalent. But Processing uses the Java 1.4 language level, and Java 1.1 introduced anonymous inner classes, which are a rough approximation.

John Feminella
A: 

Your example would look like this in Java, using anomymous inner classes:

interface Func {
    String execute(String s);
}

public String doSomething(Func someDelegate) {
    // Do something involving someDelegate.execute(String s)
}

doSomething(new Func() { public String execute(String s) { return s + "asd"; } });
doSomething(new Func() { public String execute(String s) { return new StringBuilder(s).reverse().toString(); } } });
Jesper