加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:38:09 所属栏目:Java 来源:网络整理
导读:我有以下方法使用泛型执行它收到的列表中每个项的getter: public static T,S ListS getValues(ListT list,String fieldName) { ListS ret = new ArrayListS(); String methodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(
我有以下方法使用泛型执行它收到的列表中每个项的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 ……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读