调用泛型类型的构造函数

编程入门 行业动态 更新时间:2024-10-25 20:19:33
本文介绍了调用泛型类型的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

调用泛型类型的构造函数

本文发布于:2023-11-02 15:07:38,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!