Java 泛型不能从“中自动推断类型”;这是什么;?
(这是使用Java 泛型不能从“中自动推断类型”;这是什么;?,java,generics,jackson,Java,Generics,Jackson,(这是使用Java7) 我试图在基类中放入一些JSON字符串生成方法,而不是在所有子类中都有几乎相同的代码。我尝试的第一件天真的事情是: public abstract class Base { [rest of class...] final public <T extends Base> String toJsonString() throws IOException { JacksonRepresentation<T> rep =
Java7
)
我试图在基类中放入一些JSON字符串生成方法,而不是在所有子类中都有几乎相同的代码。我尝试的第一件天真的事情是:
public abstract class Base
{
[rest of class...]
final public <T extends Base> String toJsonString() throws IOException {
JacksonRepresentation<T> rep =
new JacksonRepresentation<>(MediaType.APPLICATION_JSON, this);
return rep.getText();
}
}
公共抽象类基类
{
[其他同学…]
最后一个公共字符串toJsonString()引发IOException{
杰克森代表=
新的JacksonRepresentation(MediaType.APPLICATION_JSON,this);
返回rep.getText();
}
}
但这不会编译,给出了错误:
error: incompatible types
required: JacksonRepresentation<T>
found: JacksonRepresentation<Base>
where T is a type-variable:
T extends Base declared in method <T>toJsonString()
错误:不兼容的类型
必填项:JacksonRepresentation
发现:JacksonRepresentation
其中T是一个类型变量:
T将方法中声明的基扩展为jsonString()
所以我试了一下:
public abstract class Base
{
[rest of class...]
final public String toJsonString() throws IOException {
return jsonStringHelper(this);
}
private static <T extends Base> String jsonStringHelper(T object)
throws IOException {
JacksonRepresentation<T> rep =
new JacksonRepresentation<>(MediaType.APPLICATION_JSON, object);
return rep.getText();
}
}
公共抽象类基类
{
[其他同学…]
最后一个公共字符串toJsonString()引发IOException{
返回jsonStringHelper(此);
}
私有静态字符串jsonStringHelper(T对象)
抛出IOException{
杰克森代表=
新的JacksonRepresentation(MediaType.APPLICATION_JSON,object);
返回rep.getText();
}
}
这很有效。为什么呢?为什么编译器不能/没有意识到
this
的类型是一种满足t extends Base
的类型,并进行必要的解析?因为可以让Class1和Class2都扩展Base,而有人可以这样做:
Class1 class1 = new Class1();
String result = class1.<Class2>jsonStringHelper();
Class1=newclass1();
字符串结果=class1.jsonStringHelper();
因此,虽然可以保证“this”是Base的一个子类,但不能保证“this”是T的一个实例。但是
this
可能是与T
不同的派生类型。哦!是的,这让问题变得很明显。谢谢你的清楚解释。