草庐IT

java - 类型安全 : The expression of type List needs unchecked conversion to conform to List<Object[]>

coder 2024-03-02 原文

当我想启动一个 Hibernate 应用程序时,我总是收到类型安全警告。有没有一种方法可以在不使用 @SuppressWarnings("unchecked") 的情况下摆脱这种情况?

这是我的代码:

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!

最佳答案

Hibernate 的 Session.list()返回一个普通的原始 List .

将其转换为参数化集合(此处为 List<Object[]>)是完全合法的 Java 语法。但是由于泛型类型信息在运行时被清除,编译器会发出警告告诉你它不能保证这个转换实际上是有效的。 所以这只是他告诉你“嘿,你在玩火,我希望你知道你在做什么,因为我不知道”的方式。

在这种特殊情况下,您无法采取任何措施来消除此警告,但您可以负责使用 @SuppressWarnings 明确忽略它。注释。

关于java - 类型安全 : The expression of type List needs unchecked conversion to conform to List<Object[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29684859/

有关java - 类型安全 : The expression of type List needs unchecked conversion to conform to List<Object[]>的更多相关文章

随机推荐