In my game engine, I have a list of Entity objects, of which there are many subclasses (e.g. Player , Cube , Camera , etc.). I would like to have a method in which I pass the Class object, and in the end we get a list of the same class - for example. I would like to say something like this:
List<Box> boxes = getEntities(Box.class);
So far I have this:
public List<Entity> getEntities(Class<? extends Entity> t) { ArrayList<Entity> list = new ArrayList<>(); for (Entity e : entities) { if (e.getClass() == t) { list.add(e); } } return Collections.unmodifiableList(list); }
But, of course, returns List of Entity s, which means that every instance in the List must be added to the Box class. Is there a way to do it right in Java?
source share