Purus
Purus

Reputation: 5799

Java Mapping Class and List to Generic Types

I am trying to create a method which accepts a class as parameter and do some operation and return a list of same class.

I am trying to use Generics and have the below code.

Question: What should I do to map the provided class to the BeanListProcessor type and List ?

NOTE: This code is not correct and will produce syntax errors. This is a kind of template to explain my requirement.

public static List<?> process(Class<?> bean) {

    List<?> rows = new ArrayList<>();

    BeanListProcessor<bean> processor = new BeanListProcessor<bean>(bean.getClass());

    ....
    return rows;
}

Upvotes: 3

Views: 465

Answers (1)

Alexandre Dupriez
Alexandre Dupriez

Reputation: 3036

You may want to define a generic type at method level - if you want to return instances of the type provided as argument in the returned list.

public static <T> List<T> process(Class<T> beanClass) {
    List<T> rows = new ArrayList<>();
    BeanListProcessor<T> processor = new BeanListProcessor<T>(beanClass);
    ...
    return rows;
}

Upvotes: 5

Related Questions