方便的方式来编写指向其实现者的通用接口 [英] Convenient way to write generic interface that points out to its implementor
问题描述
public interface可更新< T> {
void updateData(T t);
}
我想指出的是只有实现者的实例可以在updateData中传递( T $)
所以,我必须写这样的东西:
public class Office实现可更新< Office> {
@Override
public void updateData(Office office){
//若要更改已实施方法的主体,请使用File |设置|文件模板。
}
...
...
...
}
但看起来有点难看。你有更好的变体吗?
人们一直在寻求This类型,主要用于流畅的API。它可能永远不会成功。但我认为可以建立一个约定 - 命名类型变量这个
来表示这个
的类型。因此,读者可以看到 This
,并确切知道它应该是什么;误用不太可能
public interface可更新< This> {
void updateData(This t);
}
//任何实现Updatable的Foo必须提供This = Foo
public class Office implements Updatable< Office>
自 必须是
Updatable< This>
,人们经常表达这个约束
public interface Updatable<这扩展了可更新< This>>
我认为这不是必要的,不应该这样做。命名约定这个
足够好。
该限制不够严格,以防止滥用。例如
public interface Foo< T extends Foo< T>>
公共类Foo1实现Foo< Foo1> // good,用途
public class Foo2实现Foo< Foo1> //编译!但不是预期的
Is there in java a way to write generic interface what points out to the implementor of such interface in more convenient way?
For example I've write interface:
public interface Updatable<T> {
void updateData(T t);
}
I want to point out that only instance of implementor can be passed in updateData(T t) method.
So, i have to write something like this:
public class Office implements Updatable<Office> {
@Override
public void updateData(Office office) {
//To change body of implemented methods use File | Settings | File Templates.
}
...
...
...
}
But seems it is a little ugly. Do you have better variants?
People have been asking for the "This" type, mostly for fluent APIs. It's probably never gonna make it. But I think it's ok to just establish a convention - name the type variable This
to represent the type of this
. So readers see This
and know exactly what it is supposed to be; misuse is unlikely
public interface Updatable<This> {
void updateData(This t);
}
// any Foo implementing Updatable must supply This=Foo
public class Office implements Updatable<Office>
Since This
must be a subtype of Updatable<This>
, people often express that constraint
public interface Updatable<This extends Updatable<This>>
I think it is not necessary, and should not be done. The naming convention of This
is good enough.
That constraint is not strict enough either to prevent misuse. For example
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
这篇关于方便的方式来编写指向其实现者的通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!