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");
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:
You can also look at the source code in the repository here:
Please let me know if you find any bugs or have any feature requests.
2 thoughts on “Java Delegates”
hey what happened to the files?
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: