dimanche 15 janvier 2017

Add an object of unknown class to ArrayList with reflection

So I have an ArrayList of objects of unknown type extending Entity (my own class; not to be confused java.swing.text.html.parser.Entity) for reasons unrelated to this problem.

private ArrayList<? extends Entity> listedEntities = new ArrayList<>();

This is in a class that in its constructor receives a String and assigns it to the field entityClass.

At some point I am executing the following piece of code:

    Class<?> clazz = Class.forName(this.entityClass);
    Object newEntity = clazz.newInstance();

    listedEntities.add(newEntity);

Naturally, this doesn't work as the ArrayList is expecting an object of a class extending Entity and newEntity is of Object. So first thing was to try casting.

listedEntities.add(Class.forName(this.entityClass).cast(newEntity));

Also doesn't work. And after a few minutes not finding an answer I am here typing this.

The exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method add(capture#8-of ? extends Entity) in the type ArrayList<capture#8-of ? extends Entity> is not applicable for the arguments (capture#9-of ?)





Aucun commentaire:

Enregistrer un commentaire