泛型不是从"this"自动推断类型的?

Qua*_*nic 4 java generics jackson

(这是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();
    }    
}
Run Code Online (Sandbox Code Playgroud)

但那不会编译,给出错误:

error: incompatible types
required: JacksonRepresentation<T>
found:    JacksonRepresentation<Base>
where T is a type-variable:
T extends Base declared in method <T>toJsonString()
Run Code Online (Sandbox Code Playgroud)

所以我尝试了这个:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作得很好.这是为什么?为什么不能/不能编译器意识到this类型是满足T extends Base并做必要的解决方案的类型?

Aff*_*ffe 6

因为你可以让Class1和Class2都扩展base,有人可以这样做:

Class1 class1 = new Class1();

String result = class1.<Class2>jsonStringHelper();
Run Code Online (Sandbox Code Playgroud)

因此,虽然保证'this'是Base的子类,但不能保证'this'是T的实例.