【发布时间】:2012-03-11 08:20:29
【问题描述】:
我正在尝试正确理解泛型,并且我编写了一个非常简单的工厂,但我不知道如何绕过这两个警告(我已经很好地抱怨了,但可能我不是使用正确的术语进行搜索)。哦!而且我不想仅仅禁止警告 - 我很确定应该可以正确做到这一点。
- 类型安全:构造函数 simpleFactory(Class) 属于原始类型 simpleFactory。对泛型 simpleFactory 的引用应该被参数化
- simpleFactory 是原始类型。对泛型 simpleFactory 的引用应该被参数化
我试图解决这个问题的所有构造实际上都无法编译——这似乎是我能得到的最接近的。生成警告的是标记为 ++++ 的行(在 Eclipse Indigo 上用于 android 项目)
我意识到周围有一些优秀的对象工厂,但这是关于理解语言而不是实际制作工厂;)
这里是来源:
import java.util.Stack;
public class simpleFactory<T> {
private Stack<T> cupboard;
private int allocCount;
private Class<T> thisclass;
public static simpleFactory<?> makeFactory(Class<?> facType) {
try {
facType.getConstructor();
} catch (NoSuchMethodException e) {
return null;
}
+++++ return new simpleFactory(facType);
}
private simpleFactory(Class<T> facType) {
thisclass = facType;
cupboard = new Stack<T>();
}
public T obtain() {
if (cupboard.isEmpty()) {
allocCount++;
try {
return thisclass.newInstance();
} catch (IllegalAccessException a) {
return null;
} catch (InstantiationException b) {
return null;
}
} else {
return cupboard.pop();
}
}
public void recycle(T wornout) {
cupboard.push(wornout);
}
}
【问题讨论】:
标签: java generics objectfactory