Adding an implementation to a Java Interface ...

This mostly an appreciation of Kohsuke's expression of creativity. Amidst the fight of dependency injection frameworks (don't get me wrong, they are all nice), Kohsuke has delivered this gem in HK2.

As an idea, this is similar to what's called a Mixin. But a Java implementation of that idea was something that caught my eye.

As we know, a Java interface has methods that describe the behavior of the classes implementing that interface. So, a Java interface like this:

interface Greeter {
  String void getName();
  void greet();
}
when handled "normally", can be implemented by a class that provides some implementation of both these methods. Now, if we were to add another method:
void byeBye();

to the interface, all implementing class must change and need to be recompiled. What if the interface had an interesting feature that enables it to build on top of an existing set of methods? Wouldn't that be nice? Of course it will be nice. Something like this:

void byeBye() {
  System.out.println("GoodBye, " + getName());
}

But who can provide this implementation? The very interface. Yes, the interface will provide the code. Here's how:

interface Greeter {
  String void getName();
  void greet();

  @DuckTyped  //this is how it is named in HK2. It could be named Mixin
  void byeBye();

  static class Duck {
    public static void byeBye(Greeter stateHolder) {
      System.out.println("GoodBye, " + stateHolder.getName());
    }
  }
}
Thus, if it can be carefully arranged that when a caller does anImplOfGreeter.byeBye(), the magical inversion occurs and what gets called is this static implementation delegating to anImplOfGreeter itself for some of the methods. If you think about this, it is so simple, and elegant.

Yes, you need the HK2 machinery to do this, but that's less than 100 K! So, get your maven repositories set up and try it out.

In the next post, I provide exact instructions on how to do this in your Service inside GlassFish v3.

So, is this the nice feature you'll vote to put into JDK7?

Comments:

Post a Comment:
Comments are closed for this entry.
About

Welcome to my blog where mostly my work related thoughts are expressed.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today