Har*_*ezz 7 java generics type-parameter
请考虑以下设置:
我们有一个SuperType
参数化的接口,如下所示:
public interface SuperType<V> {
}
Run Code Online (Sandbox Code Playgroud)
SuperType
支持方法链接.因此它定义了另一个类型参数,它捕获每个方法返回的具体实现子类型,如下所示:
public interface SuperType<V, S extends SuperType<V, S>> {
public S doSomething();
}
Run Code Online (Sandbox Code Playgroud)
让我们考虑一下以下的实现SuperType<V, S extends SuperType<V, S>>
:
public class SubType<V> implements SuperType<V, SubType<V>> {
private final V value;
public SubType(V value) { this.value = value; }
public SubType<V> doSomething() { return this; }
}
Run Code Online (Sandbox Code Playgroud)
有人SubType<V>
使用例如字符串实例化,但提供Object
了type参数V
:
Object s = "Java Generics";
SubType<Object> x = new SubType<>(s);
Run Code Online (Sandbox Code Playgroud)
现在我们要定义另一个方法,SuperType<V, S extends SuperType<V, S>>
该方法采用更具体的类型参数V
并返回相同的实现类型,S
但现在参数化为W extends V
:
public interface SuperType<V, S extends SuperType<V, S>> {
public S doSomething();
public <W extends V, T extends SuperType<W, T>> T doMoreSpecific(Class<W> typeToken);
}
Run Code Online (Sandbox Code Playgroud)
此新接口定义旨在支持:
Object s = "Java Generics";
SubType<Object> x = new SubType<>(s);
SubType<String> y = x.doMoreSpecific(String.class);
Run Code Online (Sandbox Code Playgroud)
在这里,我很难实施SubType<V>
.我想提供的实现是:
public class SubType<V> implements SuperType<V, SubType<V>> {
private final V value;
public SubType(V value) { this.value = value; }
public SubType<V> doSomething() { return this; };
public <W extends V> SubType<W> doMoreSpecific(Class<W> typeToken) {
return new SubType<>((W) value);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
我应该如何为doMoreSpecific()
类型中的方法定义签名,SuperType<V, S extends SuperType<V, S>>
以便提供的实现
SubType<V> implements SuperType<V, SubType<V>>
是可接受的?
或者,哪种实现和接口方法定义可以解决问题?
或者,为什么我们不能用Java做到这一点?
使用以下签名:
<W extends V> SuperType<W, ?> doMoreSpecific(Class<W> typeToken);
Run Code Online (Sandbox Code Playgroud)
可能还有一些不安全的情况,我还没找到,欢迎大家批评指正!