考虑以下界面:
class SomeParamClass<T> {
public T getT() {return null;}
}
class GetThing<T, TSomeImpl extends SomeParamClass<T>> {
TSomeImpl thingcreator;
GetThing(TSomeImpl thingcreator) {
this.thingcreator = thingcreator;
}
T getThing() {
return thingcreator.get(offset);
}
TSomeImpl getOrigClass() {
return thingcreator;
}
}
这只是我已经遇到过几次的问题的示例。
在此示例中,输入 T
直接绑定(bind)到参数TSomeImpl
。如果你像这样创建它:
new GetThing<String,TSomeImpl<String>>(new TSomeImpl<String>())
参数String
被不必要地重复。它是冗余,但 Java 在这种情况下似乎需要它。
有没有办法使用泛型参数内部参数作为类型?
我编写了这个语法,有没有真正适用于此的语法?
// Pseudocode on refering to generic parameter's parameters
class GetThing<TSomeImpl extends SomeParamClass<T>, TSomeImpl::<T>> {
TSomeImpl thingcreator;
GetThing(TSomeImpl thingcreator) {
this.thingcreator = thingcreator;
}
TSomeImpl::<T> getThing() {
return thingcreator.get(offset);
}
TSomeImpl getOrigClass() {
return thingcreator;
}
}
这将比使用一样:
GetThing<TSomeImpl<String>>
不需要其他参数。
澄清一下:如何重写原始类,使其只有一个泛型参数 List<T>
和 T
参数是推断出来的,因为它是从 List<T>
中明确得知的。 .
最佳答案
这个怎么样
interface SomeType<T> {
T getT();
}
class SomeParamClass<T> implements SomeType<T> {
public T getT() {return null;}
}
class GetThing<T> {
SomeType<T> thingcreator;
GetThing(SomeType<T> thingcreator) {
this.thingcreator = thingcreator;
}
T getThing() {
return thingcreator.getT();
}
SomeType<T> getOrigClass() {
return thingcreator;
}
}
你可以像这样使用它
new GetThing<String>(new SomeParamClass<>());
关于java - 如何引用泛型参数自身的参数,比如T2<T>中的T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53653162/