Java – generic methods with different return types depending on the call location

I have the following methods to use generics to execute getters for each item in the list it receives:

public static <T,S> List<S> getValues(List<T> list,String fieldName) {
    List<S> ret = new ArrayList<S>();
    String methodName = "get" + fieldName.substring(0,1).toUpperCase()
            + fieldName.substring(1,fieldName.length());
    try {
        if (list != null && !list.isEmpty()) {
            for (T t : list) {
                ret.add((S) t.getClass().getmethod(methodName).invoke(t));
            }
        }
    } catch (IllegalArgumentException e) {
    } catch (SecurityException e) {
    } catch (illegalaccessexception e) {
    } catch (InvocationTargetException e) {
    } catch (NoSuchMethodException e) {
    }
    return ret;
}

If I call it this way, it works very well:

List<Integer> ids = getValues(List<MyDTO>,"id");
request.setListIds(ids);

However, if I execute it on one line, it will give me a compilation error:

request.setListIds(getValues(List<MyDTO>,"id"));

The mistake is:

Therefore, when I try to set the list directly, it converts the generic to object instead of integer Why?

Solution

This is because Java's type inference is very weak It can infer the type when you assign it directly to the variable, but it will not infer from the target parameter type, which is what you need in the second example

You can use this to solve the problem< Integer> getValues ……

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>