我想定义以下Java类:
public class DummyTemplate<S, D extends DummyTemplate<S,D>> {
S value;
D next;
public DummyTemplate(S value, D next) {
super();
this.value = value;
this.next = next;
}
public static DummyTemplate<String, DummyTemplate> factory(){
return new DummyTemplate<String, DummyTemplate>("wohoo", null);
}
}
创建,所以我可以继承:
public class DummyTemplateSubclass<S, D extends DummyTemplateSubclass<S,D>> extends DummyTemplate<S, D>
(子类的事实返回DummyTemplateSubclass)。
但是定义会产生编译错误:
Bound mismatch: The type DummyTemplate is not a valid substitute for the bounded parameter <D extends DummyTemplate<S,D>> of the type DummyTemplate<S,D>
可能是因为DummyTemplate必须有参数,那么如何定义它呢? 我收到了错误
它仅编译如下:
public static<D extends DummyTemplate<String,D>> D factory()
然后我在子类上遇到了麻烦:
public static<D extends DummyTemplateSubclass<String,D>> D factory(){
名称冲突:DummyTemplateSubclass类型的方法factory()与DummyTemplate类型的factory()具有相同的擦除,但不隐藏它
答案 0 :(得分:2)
当你制作这样的自引用模板参数时,你不能直接使用模板,因为它不断扩展:
DummyTemplate<String, DummyTemplate<String, DummyTemplate<String, ...>>>
要使用它,您必须创建一个子类:
public class DummyTemplate<S, D extends DummyTemplate<S,D>> {
S value;
D next;
public DummyTemplate(S value, D next) {
this.value = value;
this.next = next;
}
}
public class StringTemplate extends DummyTemplate<String, StringTemplate> {
public StringTemplate(String value, StringTemplate next) {
super(value, next);
}
public static StringTemplate factory() {
return new StringTemplate("wohoo", null);
}
}
答案 1 :(得分:0)
由于factory
方法为static
且DummyTemplate
的第二个参数为D extends DummyTemplate<S, D>
,因此您需要声明一个新的泛型类型,如下所示:
public static <T extends DummyTemplate<String, T>> DummyTemplate<String, T> factory() {
return new DummyTemplate<String, T>("wohoo", null);
}
然后子类编译得很好:
public class DummyTemplateSubclass<S, D extends DummyTemplateSubclass<S, D>> extends DummyTemplate<S, D> {
public DummyTemplateSubclass(S value, D next) {
super(value, next);
}
public static <T extends DummyTemplateSubclass<String, T>> DummyTemplateSubclass<String, T> factorySubclass() {
return new DummyTemplateSubclass<String, T>("wohoo", null);
}
}
如果您要从static
中删除factory
关键字,则代码会简化:
public class DummyTemplate<S, D extends DummyTemplate<S, D>> {
S value;
D next;
public DummyTemplate(S value, D next) {
this.value = value;
this.next = next;
}
public DummyTemplate<String, D> factory() {
return new DummyTemplate<String, D>("wohoo", null);
}
}
public class DummyTemplateSubclass<S, D extends DummyTemplateSubclass<S, D>> extends DummyTemplate<S, D> {
public DummyTemplateSubclass(S value, D next) {
super(value, next);
}
@Override
public DummyTemplateSubclass<String, D> factory() {
return new DummyTemplateSubclass<String, D>("wohoo", null);
}
}