Java 类型安全:List 类型的表达式需要未经检查的转换以符合 List<Object[]>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29684859/
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
Type safety: The expression of type List needs unchecked conversion to conform to List<Object[]>
提问by Hakan Kiyar
Im getting always a type safety warning when I want to start a Hibernate application. Is there a method to get rid of this without using @SuppressWarnings("unchecked")
?
当我想启动 Hibernate 应用程序时,我总是收到类型安全警告。有没有一种方法可以在不使用的情况下摆脱这种情况@SuppressWarnings("unchecked")
?
here is my Code:
这是我的代码:
Configuration config = new Configuration();
config.addAnnotatedClass(Employee.class);
config.configure("hibernate.cfg.xml");
new SchemaExport(config).create(false, false);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(serviceRegistry);
Session session = factory.getCurrentSession();
session.beginTransaction();
Query q = session
.createQuery("SELECT e.empId,e.empName FROM Employee e");
@SuppressWarnings("unchecked")
List<Object[]> list = q.list(); <-- here is the problem!
采纳答案by Olivier Croisier
Hibernate's Session.list()
returns a plain, raw List
.
HibernateSession.list()
返回一个普通的原始List
.
It is perfectly legal Java syntax to cast it to a parameterized collection (List<Object[]>
here). But due to the fact that generic type infos are wiped out at runtime, the compiler will emit a warning to tell you it cannot guarantee this cast will actually be valid.
So it's just his way to tell you "Hey, you're playing with fire here, I hope you know what you do, because I don't".
将其强制转换为参数化集合是完全合法的 Java 语法(List<Object[]>
此处)。但是由于泛型类型信息在运行时会被清除,编译器会发出警告,告诉你它不能保证这个转换实际上是有效的。所以这只是他告诉你“嘿,你在这里玩火,我希望你知道你在做什么,因为我不知道”的方式。
In this particular case, you can't do anything to eliminate this warning, but you can take the responsibility of explicitely ignoring it by using the @SuppressWarnings
annotation.
在这种特殊情况下,您无法采取任何措施来消除此警告,但您可以通过使用@SuppressWarnings
注释承担明确忽略它的责任。
回答by nestorishimo10
No, there is no way to remove it unless you make q.list() exactly a List<Object[]>
不,除非您使 q.list() 恰好是一个,否则无法删除它 List<Object[]>
回答by Thomas
You can force the cast to make the warning go away, but much like suppressing the warning it hides a potential issue since q.list() isn't guaranteed to return that exact type.
您可以强制强制转换使警告消失,但就像抑制警告一样,它隐藏了一个潜在的问题,因为 q.list() 不能保证返回那个确切的类型。
List<Object[]> list = (List<Object[]>)q.list();