Bernd's Angle

« Previous day (Sep 10, 2006) | Main | Next day (Sep 12, 2006) »

http://blogs.sun.com/bangle/date/20060911 Monday September 11, 2006

You know @Override, now meet @Implement

Isn't it wonderful that in Java 5 you can use the @Override annotation to indicate that a given method does override another previously specified method? Personally, I find it very handy to know whether any given method you are looking at branches off into a new direction or whether it continues an existing train of thought that is inherited from the super class. If you are still unconvinced, I recommend to at least give it a try. For some deeper insights, you may want to read Peter Ahé's blog entry on the @Override subject.

If you agree with me so far, then I think we should wonder what might indicate whether a method is an implementation of an interface method. Nothing? You have to look it up in the source code, hoping there are not too many interfaces to read until you come to the conclusion whether your new method more or less accidentally implements one of their methods or not. Maybe when writing a method signature, you misspelled the method name or used a subtly incompatible parameter type, yet you did want to implement a particular interface?

One day I asked myself: it is great that there is support for better tracking of overriding, but why should implementing interface methods then remain in the orphanage of obscurity?

So, I went about defining the @Implement annotation. This annotation has a parameter of type Class, which takes the .class literal of an interface your method is implementing as an argument. For example, you can write:

    Runnable myRunnable = new Runnable() {
        @Implement(Runnable.class)
        public void run() { ... }
    }
Hm, just even more clutter in the already verbose Java syntax, you think? Maybe so, but wait until you have used this in a class with a lot of interfaces and a bunch of methods it defines, some of which implement interfaces, some don't. For plenty of examples, take a look at the source code advertised by my previous blog entry.

The parameter of @Implement is supposed to indicate the interface that first declares the original method, not any intermittent overriding interface method. But what if a method incidentally implements several interfaces that list the same signature independently? My take on this so far is that you get away with referring to any one of them. Since those interface methods better mean the same thing if there are several of them or else you have huge problems anyway, it should not matter which one you get a hold of for providing an idea of what the purpose of your added method might be.


Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.