【 在 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.
c实际是什么类型,new出来的就是什么类型,可以被转换成Shape是因为他是父类
:
: 求指教
: --
:
: ※ 来源:·水木社区
http://www.mysmth.net·[FROM: 223.166.166.*]
--
FROM 180.167.95.*