Equivalent of C# anonymous methods in Java?

Callum Rogers picture Callum Rogers · Aug 27, 2009 · Viewed 23.4k times · Source

In C# you can define delegates anonymously (even though they are nothing more than syntactic sugar). For 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).

Answer

Michael Lloyd Lee mlk picture Michael Lloyd Lee mlk · Aug 27, 2009

Pre Java 8:

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();
      }
   });

Java 8 and above:

Java 8 adds lambda expressions to the language.

    doSomething((t) -> t + "asd");
    doSomething((t) -> new StringBuilder(t).reverse().toString());