I want to define generic static method in my one of project.
Requirement is to method return type to be one of method parameter.
The below is my solution.
public static <T> List<T> convertMapToAttribute(Class<T> attrClass, T attr) {
List<T> list = null;
if (attrClass.equals(String.class)) {
list = (List<T>) new ArrayList<String>();
list.add(attr);
} else if (attrClass.equals(Integer.class)) {
list = (List<T>)new ArrayList<Integer>();
list.add(attr);
}
return list;
}
I have two questions.
- Can we avoid this waring “warning: [unchecked] unchecked cast”
without adding @SuppressWarnings(“unchecked”)? - Is there any other elegant way to solve this above problem
By having
Class<T>as a parameter, the way to do a checked cast (and skip the annoying warning) is to invokeattrClass.cast()which will throwClassCastExceptionif the casting fails. In this case,Tshould be eitherStringorInteger.The problem here is that you’re doing an unchecked cast from a list of
Tto a list of eitherStringorIntegerwhen you should define the list directly and add the element using a cast:And the same goes for Integer.
There’s something weird with your method tough (I don’t understand the intention, actually), you’re creating a list of elements from a type that you’re also passing a parameter… Shouldn’t this work as well? (since you create a list of
Ttypes and add an element ofTtype).