Java 如何使用嵌套的模板参数编写类?
我想知道如何用Java编写一个具有嵌套模板参数的类。这描述了嵌套的模板参数,但假设将使用通配符。我想命名所有涉及的类型,所以我不想使用通配符。注意,我知道通配符用于协方差。只要我知道模板类型是由哪些类型组成的,我就完全同意模板类型是不变的。下面是一个编译的代码示例,但没有提供我想要的所有信息Java 如何使用嵌套的模板参数编写类?,java,templates,generics,Java,Templates,Generics,我想知道如何用Java编写一个具有嵌套模板参数的类。这描述了嵌套的模板参数,但假设将使用通配符。我想命名所有涉及的类型,所以我不想使用通配符。注意,我知道通配符用于协方差。只要我知道模板类型是由哪些类型组成的,我就完全同意模板类型是不变的。下面是一个编译的代码示例,但没有提供我想要的所有信息 public class Parent<B> { public B b; public Parent(B b) { this.b = b; } }
public class Parent<B> {
public B b;
public Parent(B b) {
this.b = b;
}
}
public class Child<B> extends Parent<B> {
public Child(B b) {
super(b);
}
}
public class Foo<ParentType extends Parent, B> {
public ParentType parent;
public B otherItem;
public Foo(ParentType parent, B otherItem) {
this.parent = parent;
this.otherItem = otherItem;
}
}
public class Main {
public static void main(String[] args) {
Parent<String> stringParent = new Parent<>("hello");
Child<Integer> intChild = new Child<>(5);
Foo<Parent, String> foo = new Foo<>(stringParent, "bonjour");
Foo<Child, Integer> childFoo = new Foo<>(intChild, 42);
Object b = foo.parent.b;
System.out.println(b + ", " + b.getClass());
}
}
或者类似的东西,显式地强制将parent
的类型链接到B
,但IntelliJ抱怨类型“ParentType”没有类型参数,编译器给出错误:
Error:(5, 12) java: unexpected type
required: class
found: type parameter ParentType
上面标记了发生错误的位置。这是因为您没有在此处指定Parent
的类型参数:
@如果你读了janos的答案,它会告诉你下一个答案,你知道他是怎么提到把父母改成父母的。。。东西在滴答滴答地响吗?@Snickers3192对不起,东西没有滴答滴答地响。我已经尝试将
添加到类的各个部分,但这只会导致错误。如果您想提供更多信息,我的后续问题是:您需要在Foo声明的开头向Parent添加类型参数。顺便说一下,您的子类是多余的。您应该认真考虑如何在类层次结构的设计中使用继承。有用提示:如果不向继承的类添加任何方法,则可能不需要继承。
Error:(5, 12) java: unexpected type
required: class
found: type parameter ParentType
Foo<Parent, String> foo = new Foo<>(stringParent, "bonjour");
Foo<Child, Integer> childFoo = new Foo<>(intChildBar, 42);
Object b = foo.parent.b;
Foo<Parent<String>, String> foo = new Foo<>(stringParent, "bonjour");
Foo<Child, Integer> childFoo = new Foo<>(intChildBar, 42);
String b = foo.parent.b;