我想通用化返回 泛型基类的工厂方法。它的工作原理,但我得到 “BaseClass是一种原始类型...”的警告。Java - 返回通用基类型的工厂方法
我已经通过通用方法, Java文档阅读,但我还没有完全得到如何做到这一点。
下面是一些代码:
级#1
//base abstract class
public abstract class BaseFormatter<T>
{
public abstract String formatValue(T value);
}
类#2
//two implementations of concrete classes
public class FooFormatter extends BaseFormatter<Integer>
{
@Override
public String formatValue(Integer value)
{
//return a formatted String
}
}
类#3
public class BarFormatter extends BaseFormatter<String>
{
@Override
public String formatValue(String value)
{
//return a formatted String
}
}
工厂方法在一个单独的类
public static BaseFormatter getFormatter(Integer unrelatedInteger)
{
if (FOO_FORMATTER.equals(unrelatedInteger))
return new FooFormatter();
else if (BAR_FORMATTER.equals(unrelatedInteger))
return new BarFormatter();
//else...
}
电话工厂方法从其他地方中的代码
BaseFormatter<Integer> formatter = getFormatter(someInteger);
formatter.formatValue(myIntegerToFormat);
的问题是getFormatter()方法警告BaseFormatter是 原始类型,它是。我已经尝试过各种各样的东西,比如BaseFormatter 等。当然,我希望返回类型是通用的,如调用方法中声明的 BaseFormatter。
请注意,格式化程序类型不是基于类的类型。例如并非所有Integer 值都使用FooFormatter格式化。有两种或三种不同的方法可以对整数(或字符串或列表)进行格式化。这就是param unrelatedInteger的用途。
在此先感谢您的任何反馈意见。
简单的答案:Java类型系统无法安全地表达您想要的约束。这意味着你不能摆脱这个演员的警告。 – millimoose