2

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 :)

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

ok, than my <T> class should have a static newInstance(), right?
@user1908375 Class<T> already provides newInstance() method. You do need a parameterless constructor in order for this to work.
...only if the class has a public default (no-args) constructor.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.