如果我有一个这样的抽象类:
public abstract class Item { private整数值; public Item() { value = new Integer(0); } public Item(Integer value) { this.value = new Integer(); $ b $ p $ b一些派生自Item的类如下所示: p>
public class Pencil extends Item { public Pencil() { super (); } 公共铅笔(整数值) { super(value); } }我不明白为什么我不能打电话给使用泛型的构造函数:
public class Box< T extends Item> { T item; public Box() { item = new T(); //这里出现错误} }我知道那是可能有一个没有构造函数的类型,但这种情况是不可能的,因为Pencil具有不带参数的构造函数,而Item是抽象的。 但是我从eclipse得到这个错误: 不能实例化类型T 我不明白为什么,以及如何避免这种情况?没有办法使用Java类型系统来强制类层次结构对其子类的构造函数具有统一的签名。
考虑:
public class ColorPencil extends Pencil {私人颜色的颜色; public ColorPencil(Color color) { super(); this.color = color;这使得ColorPencil成为一个有效的T(它扩展了Item) 。但是,这种类型没有无参数构造函数。因此,T()是无意义的。
要做你想做的事,你需要使用反射。您无法从编译时错误检查中受益。
If I have an abstract class like this:
public abstract class Item { private Integer value; public Item() { value=new Integer(0); } public Item(Integer value) { this.value=new Integer(); } }And some classes deriving from Item like this:
public class Pencil extends Item { public Pencil() { super(); } public Pencil(Integer value) { super(value); } }I have not understood why I can't call the constructor using a generic:
public class Box <T extends Item> { T item; public Box() { item=new T(); // here I get the error } }I know that is possible to have a type which hasn't a constructor, but this case is impossible because Pencil has the constructor without parameters, and Item is abstract. But I get this error from eclipse: cannot instanciate the type T I don't understand why, and how to avoid this?
解决方案There is no way to use the Java type system to enforce that a class hierarchy has a uniform signature for the constructors of its subclasses.
Consider:
public class ColorPencil extends Pencil { private Color color; public ColorPencil(Color color) { super(); this.color=color; } }This makes ColorPencil a valid T (it extends Item). However, there is no no-arg constructor for this type. Hence, T() is nonsensical.
To do what you want, you need to use reflection. You can't benefit from compile-time error checking.
更多推荐
调用泛型类型的构造函数
发布评论