(这是与Java 7
)
我试图在我的基类中放置一些 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();
}
}
但这不会编译,给出错误:
error: incompatible types
required: JacksonRepresentation<T>
found: JacksonRepresentation<Base>
where T is a type-variable:
T extends Base declared in method <T>toJsonString()
所以我尝试了这个:
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();
}
}
效果很好。这是为什么?为什么编译器不能/没有意识到 ofthis
的类型是满足T extends Base
并进行必要解析的类型?