Question

I want to do something like this:

public List<?> queryProducts (String type) {
    Product p = Product.getProductByType(type);
    List response = null;
    if (p instanceof Dishwasher)
        response = new ArrayList<Dishwasher>();
    if (p instanceof Refrigerator)
        response = new ArrayList<Refrigerator>();
    // ...and so on

    return response;
}

How can I do this without going through every subclass? Is there something like this?

List<classOf(p)> response = new ArrayList<classOf(p)>();
Was it helpful?

Solution

Instead of accepting the String type, accept a Class parameter with a generic type parameter.

public <P extends Product> List<P> queryProducts (Class<P> clazz) {

    List<P> response = new ArrayList<P>();
    ...
    return response;
}

The caller can execute

Product p = Product.getProductByType(type);

to get the object, and then call getClass() to pass in the Class necessary.

OTHER TIPS

Just create:

List<Product> response = new ArrayList<Product>();

and add items there in order to keep abstraction

If you want to do this in a typesafe way you have to use a Class parameter instead of a String

E.g.

public <T extends Product> List<T> queryProducts (Class<T> type) {
    Product p = Product.getProductByType(type); // needs change
    List response = new ArrayList<T>()
    ...    
    return response;
}

You can then call the method this way:

List<Refrigerator> list = queryProducts(Refrigerator.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top