[英]Filling a generic List with objects of a subclass of an abstract class
Let's say we do have an abstract class called Figure
and a static method addFigure
inside. 假设我们确实有一个名为Figure
的抽象类,并且内部有一个静态方法addFigure
。 addFigure
should fill an existing list with objects of user-specified type. addFigure
应该使用用户指定类型的对象填充现有列表。
public abstract class AbstractFigure {
public static <T extends AbstractFigure> void addFigure(List<T> list, Class<T> clazz, int n)
{
for (int i = 0; i < n; i++) {
try {
T obj = clazz.newInstance();
list.add(obj);
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
}
}
Then we have a subclass, Square
. 然后我们有一个子类Square
。
public class Square extends AbstractFigure {
}
The invocation is as follows: 调用如下:
public class GenericsProblem{
public static void main(String[] args) {
ArrayList<Square> arrayListSquare = new ArrayList<>();
AbstractFigure.addFigure(arrayListSquare, Square.class, 12);
}
}
The code works correctly and the list is filled with Squares
, as I do assume. 如我所假设的那样,代码可以正常工作,并且列表中填充了Squares
。
Now, I'd like to re-make AbstractFigure
so instead of working on an existing list, it'll create and return one, as in: 现在,我想重新制作AbstractFigure
以便代替处理现有列表,而是创建并返回一个列表,如下所示:
public abstract class AbstractFigure {
public static <T extends AbstractFigure> List<T> addFigure(Class<T> clazz, int n)
{
List<T> genList = new ArrayList<>();
for (int i = 0; i < n; i++) {
try {
T obj = clazz.newInstance();
genList.add(obj);
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
return genList;
}
}
Is that even possible and if so, how could I invoke it? 这是否有可能,如果可以,我该如何调用它?
Yes, it is possible. 对的,这是可能的。 You just need to assign the return value to a variable. 您只需要将返回值分配给变量。
List<Square> arrayListSquare = addFigure(Square.class, 12);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.