Java:实例化一个没有默认构造函数的泛型类 [英] Java: Instantiating a generic class with no default constructor
问题描述
public class BaseTable< T extends TableEntry>
{
保护int mRows;
保护int mCols;
protected ArrayList< T> mEntries;
public BaseTable(int rows,int cols)
{
mRows = rows;
mCols = cols;
mEntries = new ArrayList< T>();
for(int i = 0; i {
mEntries.add(new T(cols)); //这个obv。无效
实例化泛型这很难实现,但是更难的是这里 T
没有默认的构造函数,它只需要一个 int
$
我已经询问了。如果你能回答这个问题,我将不胜感激。
问题是相关的,但只有在类被假定为具有默认构造函数时才是相关的。
已经说过,你不能用
new
创建一个T的实例,所以我会使用Factory Pattern或一个原型模式
所以你的构造函数看起来像 在你的情况中,我更喜欢原型模式,因为你的TableEntry对象可能非常轻。您的代码如下所示: I am trying to do this: Instantiating generics is hard enough as it is, but what makes this even harder is that How can this be done? I have asked a follow up question here too. I'd be grateful if you could answer that as well. This question is related, but only is relevant where the classes are assumed to have a default constructor. It was already said, that you can't create an instance of T with So your constructor would look like
In your case, I would prefer the Prototype Pattern, because your TableEntry objects are probably very light-weight. Your code would look like:
这篇关于Java:实例化一个没有默认构造函数的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
public BaseTable(int rows,int cols,LineFactory factory)$ c
public BaseTable(int rows,int cols,T prototype)
{
mRows =行;
mCols = cols;
prototype.setColumns(cols);
mEntries = new ArrayList< T>();
for(int i = 0; i
@SuppressWarnings(unchecked)
T newClone =(T)prototype.clone();
mEntries.add(newClone); //这个obv。工作:)
}
}
public static void main(String [] args)
{
新的BaseTable< SimpleTableEntry>(10,2 ,新的SimpleTableEntry());
}
public class BaseTable<T extends TableEntry>
{
protected int mRows;
protected int mCols;
protected ArrayList<T> mEntries;
public BaseTable(int rows, int cols)
{
mRows = rows;
mCols = cols;
mEntries = new ArrayList<T>();
for (int i = 0; i < rows; i++)
{
mEntries.add(new T(cols)); //this obv. doesn't work
}
}
}
T
here does not have a default constructor, it takes a single int
parameter in its constructor.
new
, so
I would use the Factory Pattern or a Prototype Patternpublic BaseTable(int rows, int cols, LineFactory factory)
with an appropriate instance of a factory.public BaseTable(int rows, int cols, T prototype)
{
mRows = rows;
mCols = cols;
prototype.setColumns(cols);
mEntries = new ArrayList<T>();
for (int i = 0; i < rows; i++)
{
@SuppressWarnings("unchecked")
T newClone = (T)prototype.clone();
mEntries.add(newClone); //this obv. does work :)
}
}
public static void main(String[] args)
{
new BaseTable<SimpleTableEntry>(10, 2, new SimpleTableEntry());
}