内部类作为“明智的”接口的默认值?
我正在扩展现有内部框架的一部分。框架的某些部分使用包含内部类的接口定义。接口用作注解的参数值,内部类作为默认值提供。界面如下所示:
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);
}
这就是用法:
public @interface Adapt {
Class<? extends Adapter<?, ?>> with() default Adapter.IDENTITY.class;
}
虽然用法看起来很简洁,但这种构造似乎违背了 Java 接口的“契约”概念,并且对于必须处理代码的下一个开发人员来说可能是违反直觉的。
在这种情况下,最佳做法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

这是最好的做法。在某些情况下,静态最终内部类包含一些确实可以定位特定实例的静态方法。
编辑:请记住,接口和内部类是两种完全独立的类型,后者仅与前者具有共同的前缀。
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.