【问题标题】:What should be the return type of generic type implementation in javajava中泛型类型实现的返回类型应该是什么
【发布时间】:2015-04-17 10:26:52
【问题描述】:

参考下面的代码 sn-p,我有一个接口Splitter,它接受泛型类型参数TV。有一种实现是CompanySplitterImpl。可能有很多这样的实现。

public interface Splitter<T, V> {
    V[] split(T arg);
}

public class CompanySplitterImpl
implements Splitter<Company, Department> {

    @Override
    public Department[] split(Company comp) {

        return comp.getDepartment();
    }
}

我正在尝试编写一个工厂方法,它根据传入工厂方法的关键参数值返回不同的实现。

// Factory method to return different Implementation of Splitter
// (Is Splitter return type correct?)
public static Splitter getSplitter(String key) {

    return new CompanySplitterImpl(); // Is this correct?
}

我的问题是返回Splitter&lt;K, V&gt;的不同实现实例的正确方式是什么?

// Client to call factory method...
// Not sure what will be type argument for Splitter type
Splitter<?> split = getSplitter("dummyKey");

在客户端,Splitter 类型的类型参数是什么?

【问题讨论】:

  • 您是否认同使用String 作为密钥的想法?请注意,Splitterraw type,可能不是一个好主意。您正在失去类型安全性。相关:"Avoid unchecked assignment in a map with multiple value types?"
  • 另外,你应该尽量避免使用泛型类型的数组——改用List&lt;V&gt;。原因有点复杂,但基本上泛型可以很容易地避免泛型的类型安全优势。
  • CompanySplitterImplSplitter&lt;Company, Department&gt;,正如您定义的那样。

标签: java generics return-type


【解决方案1】:

Splitter 是原始类型。您不应该使用原始类型。由于键(String)不携带类型信息,因此无法从传递给getSplitter 的参数推断类型参数。因此,避免原始类型的唯一方法是使返回类型为Splitter&lt;?, ?&gt;

这很丑陋,并迫使方法的调用者强制转换:

Splitter<Company, Department> split = (Splitter<Company, Department>) getSplitter("dummyKey");

一个更好的方法是使用携带类型信息的键,通常的方法是使用Class&lt;T&gt;对象。

public static <T, V> Splitter<T, V> getSplitter(Class<T> key1, Class<V> key2) {

    if (key1 == Company.class && key2 == Department.class)
        return (Splitter<T, V>) new CompanySplitterImpl();

    // more cases
}

那么调用者可以这样做:

Splitter<Company, Department> split = getSplitter(Company.class, Department.class);

【讨论】:

  • 是否可以通过从一些外部配置文件中读取来动态传递关键信息(Company.class 和 Department.class)?
猜你喜欢
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多