30

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).

nawfal
  • 70,104
  • 56
  • 326
  • 368
Callum Rogers
  • 15,630
  • 17
  • 67
  • 90
  • [A q on delegates in general in Java](http://stackoverflow.com/questions/44912/java-delegates) – nawfal Jul 04 '14 at 05:11

6 Answers6

61

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());
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
13

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
  • 7,231
  • 1
  • 26
  • 29
4

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
  • 202,709
  • 46
  • 318
  • 350
3

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
  • 303,634
  • 46
  • 339
  • 357
3

For example :

public class Delegate
{
    interface Func
    {
        void execute(String s);
    }

    public static void doSomething(Func someDelegate) {
        someDelegate.execute("123");
    }

    public static void main(String [] args)
    {

        Func someFuncImplementation = new Func() 
        {
            @Override
            public void execute(String s) {
                System.out.println("Bla Bla :"  + s);
            }
        };

        Func someOtherFuncImplementation = new Func() 
        {
            @Override
            public void execute(String s) {
                System.out.println("Foo Bar:"  + s);
            }
        };


        doSomething(someFuncImplementation);
        doSomething(someOtherFuncImplementation);
    }
}

Output :

Bla Bla :123

Foo Bar:123

JAN
  • 21,236
  • 66
  • 181
  • 318
0

You have all forgotten here that a C# delegate first of all - is thread safe. These examples are just for a single thread App..

Most of the contemporary Apps are written on multithreaded concept.. So no one answer is the answer.

There is not an equivalent in Java

  • It isn't that what you are saying is wrong. It's correct. The problem is, this does not actually answer the question being asked---it just says all the other answers are wrong. Are you saying that there is *not* an equivalent in Java? – Cody Gray - on strike Aug 13 '17 at 13:59
  • The difference here would for most users be small. I'd even argue that the lack of multicast is a bigger difference between the two. As far as the question is phrased I believe the answers above are correct. All are clear that they are talking about the closest Java has. – Michael Lloyd Lee mlk Apr 25 '18 at 10:46
  • As references are atomic, the Java version will not crash, but you could have stale data. To make it thread safe all you need to do is add the keyword "volatile". – Michael Lloyd Lee mlk Apr 25 '18 at 10:55