Java:实例化一个没有默认构造函数的泛型类 [英] Java: Instantiating a generic class with no default constructor

查看:347
本文介绍了Java:实例化一个没有默认构造函数的泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图这样做:

  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或一个原型模式

所以你的构造函数看起来像
public BaseTable(int rows,int cols,LineFactory factory)

在你的情况中,我更喜欢原型模式,因为你的TableEntry对象可能非常轻。您的代码如下所示:

  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());
}


I am trying to do this:

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
        }
    }
}

Instantiating generics is hard enough as it is, but what makes this even harder is that T here does not have a default constructor, it takes a single int parameter in its constructor.

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 new, so I would use the Factory Pattern or a Prototype Pattern

So your constructor would look like public BaseTable(int rows, int cols, LineFactory factory) with an appropriate instance of a factory.

In your case, I would prefer the Prototype Pattern, because your TableEntry objects are probably very light-weight. Your code would look like:

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());
}

这篇关于Java:实例化一个没有默认构造函数的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆