Java 嵌套通配符泛型变量做作
给定以下Java代码:Java 嵌套通配符泛型变量做作,java,generics,java-7,nested-generics,Java,Generics,Java 7,Nested Generics,给定以下Java代码: public class Test { public static class A<T> { private T t; public A(T t) { this.t = t; } public T getT() { return t; } public void setT(T t) {
public class Test {
public static class A<T> {
private T t;
public A(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public static class B<T> {
private T t;
public B(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public static class F<T> {
private T t;
public F(T t) {
this.t = t;
}
public A<B<T>> construct() {
return new A<>(new B<>(t));
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public static void main(String[] args) {
F<?> f = new F<>(0);
// 1: KO
// A<B<?>> a = f.construct();
// 2: KO
// A<B<Object>> a = f.construct();
// 3: OK
// A<?> a = f.construct();
}
}
公共类测试{
公共静态A类{
私人T;
公共A(T){
t=t;
}
公共T getT(){
返回t;
}
公共无效集合(T){
t=t;
}
}
公共静态B类{
私人T;
公共B(T){
t=t;
}
公共T getT(){
返回t;
}
公共无效集合(T){
t=t;
}
}
公共静态F类{
私人T;
公共F(T){
t=t;
}
公共A构造(){
返回新的A(新的B(t));
}
公共T getT(){
返回t;
}
公共无效集合(T){
t=t;
}
}
公共静态void main(字符串[]args){
F=新的F(0);
//1:KO
//A=f.构造();
}
}
在Test
类的主要方法中,接收f.construct()
结果的变量的正确类型是什么?
这种类型应该类似于A
,其中…
是我要找的
上面有3行注释过的代码代表了我解决这个问题的尝试。
第一行和第二行无效。
第三个是,但是我丢失了
B
类型信息,我必须强制转换a.getT()
a>a=f.construct()正如Paul Boddington所说,code>是正确的语法。为什么要使用F=new F(0)代码>而不是,例如,F=newf(0)
因为f
的实例并不总是会影响f
。您将0作为参数传递。这是一个int
。例如,Integer
可以替换为任何类型。我现在无法检查,但我认为A>A=f.construct()代码>是您想要的。