C Sharp delegate function in Java

Porting from C# to Java – The Delegate

The delegate function is kind of cool in C# land. It allows you to pass a bunch of functions as a parameter. Java has a handful of different ways you can do this. I personally like just passing an object that implements Runnable and then have an anonymous inner class that defines the run method. The following is an example in C Sharp code and how I ported it over to Java.



This first class calls the delegate function that passes a series of functions to run to another class.

new RetryPattern(Logger).Execute(delegate
					var routingKey = myEvent.GetRoutingKey();
					IBasicProperties properties = null;
					if (durable)
						properties = bundle.Channel.CreateBasicProperties();
						properties.Persistent = true;
					bundle.Channel.BasicPublish(ExchangeName, routingKey, Mandatory, properties,
				}, delegate

These functions are executed using an Action object.

public void Execute(Action action, Action throwHandler = null) {
    action(); // Do work here
    //More stuff


The way I like to do this in Java is to pass an object that implements Runner. The following two blocks do the same as the above delegate in C#.
This is the anonymous inner class.

new RetryPattern().execute(new Runnable() {
                public void run() {
                    String routingKey = myEvent.getRoutingKey();
                    BasicProperties properties = null;
                    if (durable) {
                        properties = new AMQP.BasicProperties().builder()
                    try {
                        bundle.channel.basicPublish(exchangeName, routingKey, mandatory, properties, myEvent.getBody().getBytes("UTF-8"));
                    } catch (IOException e) {
            }, new Runnable() {
                public void run() {

And this is how it is called elsewhere.

public void execute(Runnable action, Runnable throwHandler ) {
    //More Stuff

Comments are closed.