Java 使用Hibernate Criteria时,List类型的表达式需要unchecked转换才能符合List<Student>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20664625/
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-08-13 03:26:21  来源:igfitidea点击:

The expression of type List needs unchecked conversion to conform to List<Student>, when using Hibernate Criteria

javahibernateunchecked-conversion

提问by just_a_girl

I have this piece of code that gives the warning mentioned in the title:

我有这段代码给出了标题中提到的警告:

List<Student> studentList = session.createCriteria(Student.class)
    .add(Restrictions.eq("indexNumber", indexNum))
    .list();

I've read the thread How do I fix "The expression of type List needs unchecked conversion...'?and there's a great solution by @BrunoDeFraine:

我已经阅读了线程如何修复“列表类型的表达式需要未经检查的转换...”?@BrunoDeFraine 提供了一个很好的解决方案:

public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
    List<T> r = new ArrayList<T>(c.size());
    for(Object o: c)
      r.add(clazz.cast(o));
    return r;
}

then I can just do this:

那么我可以这样做:

List<SyndEntry> entries = castList(SyndEntry.class, sf.getEntries());

This works great, but in my case I have Criteria as argument, not class and collection. My question is, can this method be adapted to have criteria as argument, or should I simply use @SuppressWarnings("unchecked")?

这很好用,但在我的情况下,我将 Criteria 作为参数,而不是类和集合。我的问题是,这种方法是否可以适用于将标准作为参数,还是应该简单地使用 @SuppressWarnings("unchecked")?

采纳答案by Taylor

Moved from comment: You want to cast a Criteria object? That makes no sense. criteria.list()returns a List, so you could just use that.

移自评论:您想投射 Criteria 对象吗?这是没有意义的。criteria.list()返回一个列表,所以你可以使用它。

The castListmethod is odd anyways, you don't gain any compile-time type-safety (it will still only fail at runtime if something is wrong), and it could slow things down, especially if the list is long. I'd just use @SuppressWarnings or live with the warning.

castList无论如何,该方法很奇怪,您不会获得任何编译时类型安全性(如果出现错误,它仍然只会在运行时失败),并且可能会减慢速度,尤其是在列表很长的情况下。我只是使用@SuppressWarnings 或接受警告。