【问题标题】:Generics not auto-inferring a type from "this"?泛型不会从“this”自动推断类型?
【发布时间】:2012-07-16 17:35:47
【问题描述】:

(这是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();
    }
}

而且效果很好。这是为什么?为什么编译器不能/没有意识到this 的类型是满足T extends Base 的类型并进行必要的解析?

【问题讨论】:

  • this 可能是与T 不同的派生类型。

标签: java generics jackson


【解决方案1】:

因为您可以拥有同时扩展基数的 Class1 和 Class2,并且有人可以这样做:

Class1 class1 = new Class1();

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

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

【讨论】:

  • 天啊!是的——这让问题变得非常明显。感谢您的明确解释。
猜你喜欢
  • 2015-08-07
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多