4

(这是与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并进行必要解析的类型?

4

1 回答 1

6

Because you can have Class1 and Class2 that both extend base, and someone could do this:

Class1 class1 = new Class1();

String result = class1.<Class2>jsonStringHelper();

So while it is guaranteed that 'this' is a subclass of Base, there is no guarantee that 'this' is an instance of T.

于 2012-07-16T17:40:10.163 回答