Java:对泛化类进行子类化

时间:2010-01-25 03:53:32

标签: java generics subclass java.lang.class

我有一个泛化类,我希望子类化如下:

public class SomeTable<T extends BaseTableEntry>
    extends BaseTable<T>
{

    public SomeTable(int rows, int cols)
    {
        super(rows, cols, SomeTableEntry.class);
        //Does not compile:
        //Cannot find symbol: constructor BaseTable(int, int, java.lang.Class<blah.blah.SomeTableEntry.class>)
    }
}

...通用化超类的位置是:

public class BaseTable<T extends BaseTableEntry>
{

    public BaseTable(int rows, int cols, Class<T> clasz)
    {
        ...
    }
...
}

我理解编译器错误,但似乎无法找到解决方法,除了在SomeTable构造函数中包含额外参数。

有什么建议吗?

谢谢!

2 个答案:

答案 0 :(得分:10)

编译:

public class SomeTable extends BaseTable<SomeTableEntry> {
    public SomeTable(int rows, int cols)
    {
        super(rows, cols, SomeTableEntry.class);
    }
}

它与演员合作:

public class SomeTable<T extends BaseTableEntry> extends BaseTable<T> {
    public SomeTable(int rows, int cols)
    {
        super(rows, cols, (Class<T>)SomeTableEntry.class);
    }
}

但是我期待有人发布解释为什么编译器需要为类进行强制转换。

答案 1 :(得分:3)

如果以与基类相同的方式将SomeTable传递给它,则可以一般性地定义Class构造函数:

public class BaseTable<T extends BaseTableEntry>
{
    public BaseTable(int rows, int cols, Class<? extends T> clazz)
    {
        // ...
    }
}

class SomeTable<T extends BaseTableEntry>
extends BaseTable<T>
{
    public SomeTable(int rows, int cols, Class<? extends T> clazz)
    {
        super(rows, cols, clazz);
    }
}