Spring从4.2x升级到5.3x后出现HashSet<>类型参数无法推断错误
问题:Spring 4.2x升级到5.3x后出现
Cannot infer type arguments for HashSet<>错误 升级Spring版本后,以下代码编译报错:
public static final String SEARCH_REQ = "Search Request"; public static final String SEARCH_RES = "Search Response"; @SuppressWarnings("unchecked") private static Set<String> SEARCH_ACTIONS = new HashSet<>(CollectionUtils.arrayToList(new String[] { SEARCH_REQ, SEARCH_RES }));
原因分析
Spring两个版本中CollectionUtils.arrayToList的返回类型发生了关键变化:
- Spring 4.2x的实现返回原始类型List:
public static List arrayToList(Object source) { return Arrays.asList(ObjectUtils.toObjectArray(source)); } - Spring 5.3x的实现返回泛型通配符类型List<?>:
public static List<?> arrayToList(@Nullable Object source) { return Arrays.asList(ObjectUtils.toObjectArray(source)); }
Java编译器无法从List<?>推断出HashSet的泛型参数为String,因此抛出类型推断错误。
最佳解决方案
直接使用Arrays.asList替代CollectionUtils.arrayToList——后者本质上也是调用Arrays.asList,修改后代码更简洁且类型安全:
public static final String SEARCH_REQ = "Search Request"; public static final String SEARCH_RES = "Search Response"; private static Set<String> SEARCH_ACTIONS = new HashSet<>(Arrays.asList(SEARCH_REQ, SEARCH_RES));
此方案无需@SuppressWarnings注解,编译器能明确推断出List<String>类型,彻底避免类型安全隐患。
其他可选方案(不推荐)
如果一定要保留CollectionUtils.arrayToList的调用,可以将Set的泛型改为Set<?>,但这会丢失类型安全性:
@SuppressWarnings("unchecked") private static Set<?> SEARCH_ACTIONS = new HashSet<>(CollectionUtils.arrayToList(new String[] { SEARCH_REQ, SEARCH_RES }));
内容的提问来源于stack exchange,提问作者BoomRamada
相关产品推荐
相关产品推荐

