类型安全性:未经检查的从Object到List <SourceSystemConfig>的转换

时间:2019-09-17 14:24:51

标签: java

Type safety: Unchecked cast from Object to List<SourceSystemConfig> 

当这样做时,我看到我不想使用@SuppressWarnings("unchecked")的警告,所以我尝试了不同的方式

我尝试使用通配符Map<?,?>@SuppressWarnings("unchecked")

private SourceSystemConfig getSourceConfig(HttpServletRequest request, SourceProjectAssocation sourceSystem) throws Exception
{
            //Type safety: Unchecked cast from Object to List<SourceSystemConfig>
    List<SourceSystemConfig> sourceSystemList = (List<SourceSystemConfig>) request.getSession()
            .getAttribute(SOURCE_SYSTEM_LIST);
    if(CollectionUtils.isEmpty(sourceSystemList))
    {
        UserEntity userEntity = vendorUtils.getUserDetails(request.getRemoteUser());
        sourceSystemList =  vendorUtils.getVendorConnectionsForTenant(userEntity);
        request.getSession().setAttribute(SOURCE_SYSTEM_LIST, sourceSystemList);
    }
    Optional<SourceSystemConfig> source = sourceSystemList.stream()
            .filter(ss -> ss.getKey().equalsIgnoreCase(sourceSystem.getKey())).findFirst();
    SourceSystemConfig config = null;
    if (source.isPresent())
    {
        config = source.get();
    }
    return config;
}

List<SourceSystemConfig>
    List<SourceSystemConfig> sourceSystemList = (List<SourceSystemConfig>) request.getSession()
            .getAttribute(SOURCE_SYSTEM_LIST);
//Type safety: Unchecked cast from Object to List<SourceSystemConfig> i am getting this warnning but i don't expected this

1 个答案:

答案 0 :(得分:0)

只需存储一个SourceSystemConfig[]或您自己的可存储List<SourceSystemConfig>的可序列化类。

List<SourceSystemConfig> sourceSystemList = new ArrayList<>();
Collections.addAll(sourceSystemList, (SourceSystemConfig[]) request.getSession()
        .getAttribute(SOURCE_SYSTEM_LIST));

这避免了对具有通用参数类型的类进行强制转换。 (SourceSystemConfig[])的投射可以立即正确进行。