Java:子类化泛型类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2130100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Subclassing a genericised class
提问by bguiz
I have a genericised class that I wish to subclass as follows:
我有一个泛型类,我希望将其子类化如下:
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>)
}
}
... where the genericised superclass is:
...泛化超类是:
public class BaseTable<T extends BaseTableEntry>
{
public BaseTable(int rows, int cols, Class<T> clasz)
{
...
}
...
}
I understand the compiler error, but cannot seem to find a workaround, other than to include an extra parameter in the SomeTableconstructor.
我理解编译器错误,但似乎找不到解决方法,只能在SomeTable构造函数中包含一个额外的参数。
Any suggestions?
有什么建议?
Thanks!
谢谢!
回答by Steve B.
This compiles:
这编译:
public class SomeTable extends BaseTable<SomeTableEntry> {
public SomeTable(int rows, int cols)
{
super(rows, cols, SomeTableEntry.class);
}
}
It works with a cast:
它与演员一起工作:
public class SomeTable<T extends BaseTableEntry> extends BaseTable<T> {
public SomeTable(int rows, int cols)
{
super(rows, cols, (Class<T>)SomeTableEntry.class);
}
}
but I'm looking forward to someone posting the explanation for why the compiler requires the cast for the class.
但我期待有人发布解释为什么编译器需要该类的演员表。
回答by finnw
It is possible to define the SomeTableconstructor generically if you pass Classto it the same way as you do with the base class:
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);
}
}

