槽点过于密集,我一个一个说:
* 子类对象is-a关系概念错误
Class c = list.get(0).getClass();
Shape s = (Shape) c.newInstance();
你这样得到的是一个c对应的对象而不是Shape对象。事实上Shape可以是抽象类。
Cicle is a Shape
你拿到的就是Circle对象
* 容易出错的设计
newInstance()调用的是无参构造。如果某个子类定义的构造函数有参数那么就会出错
List<Shape里可以有多个不同的子类。你的实现默认就只考虑了第一个。
* 范型错误
如果你手头的对象是List<Circle>,那你是不能将它作为一个List<Shape>传递的。
你需要将型参声明为List<? extends Shape>
【 在 tortelee (hust-wh) 的大作中提到: 】
: 标 题: ArrayList<Shape> 里add new object
: 发信站: 水木社区 (Mon Jul 12 21:36:18 2021), 站内
:
: 问题描述:
: 有一个Shape, rectangle, circle 继承此类;
: 有一个List, List<Shape>.
: 现在我想写一个方法,
: addMoreToList(ArrayList<Shape> list, int i){
:
: }
: 往list里面添加i个新对象。比如本身是list<circle>, i = 1, 那么再加入一个circle对象。
:
: 我是这么想的: 如果用反射,在方法里获得具体的shape类是可以实现的,
: Class c = list.get(0).getClass();
: 但是接下来生成对象怎么写?
: Shape s = (Shape) c.newInstance()
: 这样写的话,生成的还是shape,并不是具体的circle或者 rectangle.
:
: 求指教
: --
:
: ※ 来源:·水木社区
http://www.mysmth.net·[FROM: 223.166.166.*]
--
FROM 76.126.252.*