【问题标题】:How do I bound a generic type to 2 types that are almost completely separated in hierarchy如何将泛型类型绑定到在层次结构中几乎完全分离的 2 种类型
【发布时间】:2013-01-16 13:19:42
【问题描述】:

我该怎么做?因为你只能扩展一个类,所以它只能有一个上限。

在我的情况下,我需要将泛型类型限制在 String 和 int 中。如果我使用 Integer 包装器而不是 int 并依赖自动装箱,我可以做到,但问题是其他类也可以作为类型参数传递。

最好的方法是什么?

【问题讨论】:

  • 这听起来有点乱,就用Object吧
  • 您不能将基元用作泛型类型,无论如何您都需要使用包装类。

标签: java class generics types hierarchy


【解决方案1】:

您可以使用集合的非通用变体(例如 List),或者 更明确地List<Object> 以显示代码的意图。
将其包装在 MyList 类中,并为您想要支持的每种类型创建 add()、get() 方法:

add(Integer elem);
add(String elem);

但是 Object get() 不能输入,这样才有意义。

所以最后你也可以将 Object 与 List 一起使用,并省略包装器。

【讨论】:

  • 我建议使用 List<Object> 而不是 rawtype List,因此代码的意图很明确,您不必抑制任何警告(或者这就是您的最后一句话所说的?)
【解决方案2】:

我认为你做不到。 String 也是一个最终类和所有这些东西。正如@NimChimpsky 所说,使用 Object 本身可能会更好。另一种解决方案是两个类的包装器,但您仍然会得到一个结果对象,您可能需要对其进行转换并依赖instanceof

class StringInt {
  private String string;
  private Integer integer;

  public StringInt(String s) { this.string = s; }
  public StringInt(Integer i) { this.integer = i; }

  public Object getValue() { return string != null ? string : integer; }
}

或者使用丑陋的验证,显然,这只会在运行时应用......

class StringIntGen<T> {
  private T t;

  public StringIntGen(T t) { 
    if (!(t instanceof String) && !(t instanceof Integer)) 
      throw new IllegalArgumentException(
          "StringIntGen can only be Integer or String");
    this.t = t; 
  }

  public T getValue() { return t; }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-14
    • 2013-03-20
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多