[英]What should be the return type of generic type implementation in java
Refering to the following code snippet, I have a interface Splitter
which takes generic type parameters T
and V
. 参考下面的代码片段,我有一个接口
Splitter
,它使用通用类型参数T
和V
There is one implementation which is CompanySplitterImpl
. 有一个实现是
CompanySplitterImpl
。 There could be many such implementations. 可能有许多这样的实现。
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();
}
}
I am trying to write a factory method which returns different implementation based on a key parameter value passed in to the factory method. 我正在尝试编写一个工厂方法,该方法基于传入工厂方法的关键参数值返回不同的实现。
// 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?
}
My question is what is the correct manner of returning instance of different implementation of Splitter<K, V>
? 我的问题是返回
Splitter<K, V>
不同实现的实例的正确方式是什么?
// Client to call factory method...
// Not sure what will be type argument for Splitter type
Splitter<?> split = getSplitter("dummyKey");
At the client side, What will be the type argument for Splitter type? 在客户端,拆分器类型的类型参数是什么?
Splitter
is a raw type. Splitter
是原始类型。 You should not use raw types. 您不应该使用原始类型。 Since the key (a
String
) carries no type information, it is not possible to infer the type parameters from the argument passed to getSplitter
. 由于键(一个
String
)不包含类型信息,因此无法从传递给getSplitter
的参数中推断类型参数。 Therefore, the only way to avoid raw types is to make the return type Splitter<?, ?>
. 因此,避免原始类型的唯一方法是使返回类型为
Splitter<?, ?>
。
This is ugly and forces the caller of the method to cast: 这很丑陋,并迫使该方法的调用者进行强制转换:
Splitter<Company, Department> split = (Splitter<Company, Department>) getSplitter("dummyKey");
A better way of doing this is to use a key that carries type information, and the usual way to do this is to use Class<T>
objects. 更好的方法是使用带有类型信息的键,而通常的方法是使用
Class<T>
对象。
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
}
Then the caller could do: 然后,调用者可以执行以下操作:
Splitter<Company, Department> split = getSplitter(Company.class, Department.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.