user1908375
user1908375

Reputation: 1089

generate array list of dynamic type in java

what I have is a super class

class Geometry{
}

and two classes that extends it:

class ShapeOne extends Geometry{}

class ShapeTwo extends Geometry{}

what I want to achieve is to generate a list(read from the database) of objects of the type ShapeOne or ShapeTwo or any other that is instance of Geometry, but dynamically passing the type as a parameter, for example like:

public ArrayList< Geometry Object > getList(/**passing typeof generated list**/){
  // getting data from Database;
  return new ArrayList<typeof generated list>();
}

so the call would be then like:
 getList(ShapeTwo);

thanks for any help :)

Upvotes: 2

Views: 6789

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

You can do it by passing Class<T>, like this:

public <T extends GeometryObject> List<T> getList(Class<T> itemClass) throws Exception {
    List<T> res = new ArrayList<T>();
    for (int i = 0 ; i != 10 ; i++) {
        res.add(itemClass.newInstance());
    }
    return res;
}

Demo.

Note: the above call to newInstance assumes that the class has a parameterless constructor.

Upvotes: 4

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You cannot do that. Due to type erasure, List<Geometry> is not a super class of List<ShapeOne>. This is better explained here: Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?.

Some alternatives to solve your problem:

  • Return List<ShapeOne> or List<ShapeTwo> or List<TheExpectedClass> rather than List<Geometry>.
  • Return <T extends Geometry> List<T> and pass Class<T> clazz as argument. Probably you would need to use an additional parameter to recognize if the data recovered from database belongs to a specific subclass of Geometry.

Upvotes: 4

Related Questions