Let's say we do have an abstract class called Figure
and a static method addFigure
inside. addFigure
should fill an existing list with objects of user-specified type.
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
.
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.
Now, I'd like to re-make AbstractFigure
so instead of working on an existing list, it'll create and return one, as in:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.