java 类型安全:从 List 到 List<String> 的未经检查的强制转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38049896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:03:33  来源:igfitidea点击:

Type safety: Unchecked cast from List to List<String>

java

提问by María Belén Esteban Menéndez

I have this method where I cast the results to (List ) , but my eclipse is still complaining ! Type safety: Unchecked cast from List to List

我有这个方法,可以将结果转换为 (List),但是我的 eclipse 仍然在抱怨! 类型安全:从列表到列表的未经检查的强制转换

@Override
public List<String> getDevices(Long productId) {

        String queryString = "SELECT op.name FROM t_operation op WHERE op.discriminator = 'ANDROID' and PRODUCT =:productId ";

        try {
            Query query = getEntityManager().createQuery(queryString);
            query.setParameter("productId", productId);

            return (List<String> ) query.getResultList();


        } catch (RuntimeException re) {         
            throw re;
        }

    }

采纳答案by Jordi Castilla

You will get this warning due runtime check cast.

由于运行时检查转换,您将收到此警告。

Even if you use if(query.getResultList() instanceof List<?>)you will get this warning, so...

即使你使用if(query.getResultList() instanceof List<?>)你也会收到这个警告,所以......

  • use @SuppressWarnings("unchecked")or
  • use generics
  • 使用@SuppressWarnings("unchecked")
  • 使用泛型

回答by Lê Th?

You can sure use TypedQuery with the parameter types is String in this case. So what you need is

在这种情况下,您可以确定将 TypedQuery 与参数类型一起使用。所以你需要的是

TypedQuery<String> query = getEntityManager().createQuery(queryString, String.class); 

回答by Galya

Please don't use @SuppressWarningsand don't type cast, because these are error-prone ways to do this. Follow the advice given in the following answer to a similar question and use TypedQuery: https://stackoverflow.com/a/21354639/3657198

请不要使用@SuppressWarnings也不要类型转换,因为这些是容易出错的方法。按照以下对类似问题的回答中给出的建议并使用TypedQueryhttps: //stackoverflow.com/a/21354639/3657198

TypedQuery<SimpleEntity> q = 
    em.createQuery("select t from SimpleEntity t", SimpleEntity.class);

List<SimpleEntity> listOfSimpleEntities = q.getResultList();
for (SimpleEntity entity : listOfSimpleEntities) {
    // do something useful with entity;
}

回答by Yassin Hajaj

java-8

java-8

You may want to use this special hack to return the correct type. It works with any type of object since String#valueOf(Object)exists

你可能想使用这个特殊的技巧来返回正确的类型。它适用于任何类型的对象,因为它String#valueOf(Object)存在

try {
    Query query = getEntityManager().createQuery(queryString);
    query.setParameter("productId", productId);
    return query.getResultList().stream().map(String::valueOf).collect(Collectors.toList());
} catch (RuntimeException re) {         
    throw re;
}