简体   繁体   中英

pass generic type class to method

I want to convert List<Object[]> to List<ClassX>

For that purpose, I have created a method:

public List mapObjectArrayListToClassList(List<Object[]> objectArrayList, Class genericType){
    //some awesome logic
    return new ArrayList<genericType>();
}

I want to call the method as follows:

mapObjectArrayListToClassList(objectArrayList, ClassX.class);

I am getting compilation error:

genericType cannot be resolved to a type

Type arguments provided in generic type usages must be type names or type variables, they cannot be references to variables or expressions.

Make your method generic.

public <T> List<T> mapObjectArrayListToClassList(List<Object[]> objectArrayList, Class<T> genericType){
    //some awesome logic
    return new ArrayList<T>(); // or return new ArrayList<>(); 
}

You have to specify the generic type for the method

 public <T> List<T> mapObjectArrayListToClassList(List<Object[]> objectArrayList, Class<T> genericType)

Note: Raw types like List and Class compile in Java but don't use them, they are evil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM