调用泛型类型的构造函数 [英] Calling constructor of a generic type

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

问题描述

如果我有一个这样的抽象类:

  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

我不明白为什么,以及如何避免这种情况?

考虑:

  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.

这篇关于调用泛型类型的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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