justSaid
justSaid

Reputation: 1640

How to retrieve the class of a generic type

I have a generic methode like this one:

public class ClassName {
    public <T> List<T> methodeName(String path)
        throws FileNotFoundException {
    CSVReader reader = new CSVReader(new FileReader(path), ',', '\"');

    HeaderColumnNameTranslateMappingStrategy<T> strat = new HeaderColumnNameTranslateMappingStrategy<T>();

    strat.setType(T.class);

In the last line (T.class) eclipse is showing me this synthax-error Illegal class literal for the type parameter T.

A solution like this one proposed here: Java generics - retrieve type won't help me. The methode getClass() would only return the current class.

I'm new to generics but I'm sure there is a simple answer for this question.

Upvotes: 2

Views: 3012

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

The simple answer is: you have to pass a Class<T> argument to the method.

public <T> List<T> methodeName(String path, Class<T> clazz) throws FileNotFoundException {
    CSVReader reader = new CSVReader(new FileReader(path), ',', '\"');

    HeaderColumnNameTranslateMappingStrategy<T> strat = 
        new HeaderColumnNameTranslateMappingStrategy<T>();
    strat.setType(clazz);
}

...

ClassName cn = new ClassName();
List<Foo> foos = cn.methodeName(somePath, Foo.class);

Upvotes: 8

Related Questions