I swear I would never see he day in which I found something that Java does better than the .Net framework. Unfortunately for me today is that day. I usually don’t do Java very much because my job never calls for it and I have zero *umph* to take and learn the antiquated language and yet today as I’m working in Java for a class I learned something I’m very very jealous of that Java supports and .Net does not. Anonymous instances of interfaces.
Anyone who’s done a UI in Java has done this 1,000,000,000,000,000 times so if this is something of a “duh dumbass” moment as you read this go ahead and pass on by otherwise here is what I have.
Java events work extremely different that .Nets do. They have this concept of listeners in which one creates an object that implements the interface ActionListener and a method is nailed down on the fly such as the following code specifies.
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calculate(e);
}
});
Notice that we’re adding the ActionListener to the JButton btnCalculate and the method is being defined on the fly. In the .Net world we have similar feats for Events and anonymous types, but generally speaking we can’t say this anonymous type is of type INotifyValueChanged and pass in a dynamic object that maps the interface as is done here in Java.
I’m envious of this because it would be such a useful construct for a host of uses including but not limited to proxy objects used in TDD.
I would like also to state that the object works as a closure due to the fact that information contained in the actionPerformed method has access to everything it’s host object does.
I imagine Java geeks use this technique often and are rolling over in their Javaesque graves right now seeing that a .Net guy is envious of such a thing but credit is due where credit is due and this is just cool. Come on CLR team give me this!
0 comments:
Post a Comment