微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 根据调用位置的不同返回类型的泛型方法

我有以下方法使用泛型执行它收到的列表中每个项的getter:
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;
}

如果我这样称它,它的工作原理非常好:

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

但是,如果我在一行中执行它,它会给我一个编译错误

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

错误说:

The method setListIds(List-Integer-) in the type
MyDTO is not applicable for the arguments
(List-Object-)

因此,当我尝试直接设置列表时,它将泛型转换为Object而不是Integer.这是为什么?

解决方法

这是由于Java的类型推断非常弱.它可以在您直接分配给变量时推断出类型,但不会通过目标参数类型进行推断,这在第二个示例中是您需要的.

你可以用这个来解决这个问题.< Integer> getValues ……

原文地址:https://www.jb51.cc/java/121810.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐