MattHicks.com

Programming on the Edge

Java Delegates

Published by Matt Hicks under , , , , on Tuesday, July 01, 2008
If you're searching the internet for the title of this post you'll see a lot of people ranting about how Java doesn't have Delegate support. Though I have been one of these people, and continue to be frustrated that there is no native solution, that is not the purpose of this post.

I write this to say I've created what I would consider to be a pretty clean alternative to native delegates in Java using reflection. I created this as a feature in jSeamless and have been using it heavily for a while, but after a few people asking about support in non-jSeamless applications for my friendly Delegate support I decided I would remove it from jSeamless and make it a stand-alone API that anyone can use.

The Delegate implementation I find myself using more than anything else is MethodDelegate. It provides the ability to reference a specific method on a specific object that can be invoked. For example:
Delegate d = MethodDelegate.create(myObject, "doSomething");

d.invoke();

The invoke method takes varargs and returns an Object (or null if there is no return). The great thing about this is that you can pass it to something so it can be asynchronously be called later and keeps you from having to block while you wait for something to complete.

You can download the JARs here:

delegates.jar

delegates-src.jar

delegates-doc.jar

You can also look at the source code in the repository here:

http://captiveimagination.com/svn/public/delegates/trunk

Please let me know if you find any bugs or have any feature requests.

2 comments:

lamboap said... @ February 11, 2009 at 9:09 PM

hey what happened to the files?

Matt Hicks said... @ February 12, 2009 at 8:03 AM

The work done for this has been moved out into a new project called xjava on googlecode. It includes revised work on delegate support in Java and much much more:

http://xjava.googlecode.com

Post a Comment