java中是否有一种编写通用接口的方法,以更方便的方式向此类接口的实现者指出?
例如我写的接口:
public interface Updatable<T> {
void updateData(T t);
}
我想指出的是,只有实现者的实例可以在 updateData(T t) 方法中传递。
所以,我必须写这样的东西:
public class Office implements Updatable<Office> {
@Override
public void updateData(Office office) {
//To change body of implemented methods use File | Settings | File Templates.
}
...
...
...
}
不过好像有点丑。你有更好的变体吗?
人们一直在寻求“This”类型,主要是为了流畅的 API。可能永远也成不了了但我认为建立一个约定就可以了 - 命名类型变量This
来表示类型this
。所以读者看到This
并确切地知道它应该是什么;滥用的可能性不大
public interface Updatable<This> {
void updateData(This t);
}
// any Foo implementing Updatable must supply This=Foo
public class Office implements Updatable<Office>
Since This
必须是子类型Updatable<This>
,人们经常表达这种约束
public interface Updatable<This extends Updatable<This>>
我认为没有必要,也不应该这样做。的命名约定为This
就足够好了。
该限制也不够严格,不足以防止滥用。例如
public interface Foo<T extends Foo<T>>
public class Foo1 implements Foo<Foo1> // good, intended use
public class Foo2 implements Foo<Foo1> // compiles! but not intended
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)