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.

Example

C#

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,
						Encoding.UTF8.GetBytes(myEvent.GetBody()));
				}, delegate
				{
					ResetOnConnectionError();
					CreatePublisher();
				});

These functions are executed using an Action object.

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

Java

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() {
                @Override
                public void run() {
                    String routingKey = myEvent.getRoutingKey();
                    BasicProperties properties = null;
                    if (durable) {
                        properties = new AMQP.BasicProperties().builder()
                                .deliveryMode(2)
                                .build();
                    }
                    try {
                        bundle.channel.basicPublish(exchangeName, routingKey, mandatory, properties, myEvent.getBody().getBytes("UTF-8"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, new Runnable() {
                @Override
                public void run() {
                    resetOnConnectionError();
                    createPublisher();
                }
            });

And this is how it is called elsewhere.
[java]
public void execute(Runnable action, Runnable throwHandler ) {
    //Stuff
    action.run();
    //More Stuff
}

Leave a Reply