【问题标题】:No instance(s) of type variable(s) T exist so that List<T> conforms to Integer不存在类型变量 T 的实例,因此 List<T> 符合 Integer
【发布时间】:2017-04-22 12:15:48
【问题描述】:

在以下代码中:

return new HashSet<>(namedParameterJdbcTemplate.query(
    SOME_SQL_QUERY_STRING,
    parametersMap,
    (resultSet, rowNum) -> resultSet.getBigDecimal("GETID")
));

(resultSet, rowNum) -&gt; resultSet.getBigDecimal("GETID")) 下出现红线,并出现以下错误:No instance(s) of type variable(s) T exist so that List&lt;T&gt; conforms to Integer。有人可以帮我解释一下为什么会这样吗?

【问题讨论】:

  • resultSet 包含什么类型?这可能不是一个数字
  • 您可能需要指定“查询”函数的通用参数:(...) namedParameterJdbcTemplate.query(...
  • 我的猜测是使用 lambda 会导致 query() 的重载与您预期的不同 - 检查它使用的重载。
  • @recurf 结果集将包含 BigDecimal
  • @jiriTousek public &lt;T&gt; List&lt;T&gt; query(String sql, Map&lt;String, ?&gt; paramMap, RowMapper&lt;T&gt; rowMapper) throws DataAccessException { return query(sql, new MapSqlParameterSource(paramMap), rowMapper); } 这是查询方法过载。抱歉格式错误

标签: java generics lambda type-inference


【解决方案1】:

根本问题是(基于代码)推断出不同的(不需要的)“查询”方法的重载版本,并且作为第三个参数给出的 lambda(函数)不适合此版本的“查询”。

解决此问题的一种方法是通过提供 type 参数来“强制”您想要的查询功能:

return new HashSet<>(namedParameterJdbcTemplate.<BigDecimal>query( ...

【讨论】:

  • 供将来参考,这称为类型见证
【解决方案2】:

为您的方法调用添加显式转换

在我的情况下,我有

<T> Map<String, T> getMap(@NotNull String rootPath, @NotNull Class<T> type)

我使用它就像

LinkedHashMap<String,String> x = xmlRegestryFile.getMap("path/to/map/of/string", String.class)

但它失败并给了我这个错误,所以我通过添加转换克服了这个错误

x = (LinkedHashMap<String, String>) xmlRegestryFile.getMap("my/path", String.class)

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2018-07-31
    • 2022-10-18
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多