Inner class as "sensible" default for an interface?
I'm extending part of an existing internal framework. Some part of the framework uses an interface definition that contains an inner class. The interface is used as a parameter value for an annotation and the inner class is provided as a default value. The interface looks like this:
public interface Adapter<X,Y> {
static final class IDENTITY implements Adapter<Object, Object> {
@Override
public Object transform(Object x) {
return x;
}
@Override
public Object inverse(Object y) {
return y;
}
}
public Y transform(X x);
public X inverse(y y);
}
And this is the usage:
public @interface Adapt {
Class<? extends Adapter<?, ?>> with() default Adapter.IDENTITY.class;
}
Although the usage looks neat, this construct seems to go against 开发者_如何学运维the 'contract' concept of a Java interface and might be counter-intuitive for the next dev that has to deal with the code.
What would be the best practice in this case?
That is the best practice. There are also instances where a static final inner class contains some static methods that do f.e. locate a specific instance.
Edit: Keep in mind that the interface and the inner class are two completely separate types, the latter just has a common prefix with the former.
精彩评论