简体   繁体   中英

What is the best way to define Generic Method in Java?

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.

  1. Can we avoid this waring "warning: [unchecked] unchecked cast" without adding @SuppressWarnings("unchecked")?
  2. Is there any other elegant way to solve this above problem

The following should work fine:

List<T> list = new ArrayList<T>(); 
List<T> list = new ArrayList<>(); // Java 7

Couldn't you just do something like...

public static <T> List<T> convertMapToAttribute(Class<T> attrClass, T attr) {
    List<T> list = new ArrayList<T>(1);
    list.add(attr);
    return list;
}

instead?

UPDATE based on feedback

public static <T> List<T> convertMapToAttribute(T attr) {
    List<T> list = new ArrayList<T>(1);
    list.add(attr);
    return list;
}

By having Class<T> as a parameter, the way to do a checked cast (and skip the annoying warning) is to invoke attrClass.cast() which will throw ClassCastException if the casting fails. In this case, T should be either String or Integer .

The problem here is that you're doing an unchecked cast from a list of T to a list of either String or Integer when you should define the list directly and add the element using a cast:

if (attrClass.equals(String.class)) {
    List<String> list =  new ArrayList<String>();
    list.add(attrClass.cast(attr));
}

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 T types and add an element of T type).

public static <T> List<T> convertMapToAttribute(T attr) {
    List<T> list = new ArrayList<T>();
    list.add(attr);
    return list;
}
  1. Not to my knowledge

  2. Skip the attrClass parameter, since it actually makes the method non-generic.

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