Tom Bell
Tom Bell

Reputation: 499

How to remove 'Type Safety'/'Unchecked conversion' warning from returning generic List in Java?

I'm performing the following operation in Java using Hibernate inside my data access object:

public List<Device> getDevices() {
    return getCurrentSession().createQuery("from Device").list();
}

This gives me the following warning:

Type safety: The expression of type List needs unchecked conversion to conform to     List<Device>

In order to remove the warning I'm using

@SuppressWarnings("unchecked")

but I'm looking for a better way to remove this warning and ideally deal with something other than 'Device' from being returned from the database.

Any ideas?

Upvotes: 2

Views: 2181

Answers (3)

aweigold
aweigold

Reputation: 6879

The hibernate session object will not return a typed Query. You can utilize an EntityManager instead (which hibernate supports), which does allow you to specify type on createQuery().

Upvotes: 0

Zavior
Zavior

Reputation: 6452

Java does not have reified generics, so sadly you can not get rid of the annotations :( If you search for this on SO, one of the most often recommended solutions is to use Collections.checkedList, which might be helpful here

Upvotes: 3

Adam Arold
Adam Arold

Reputation: 30528

Since you put the spring tag in your question I assume that you are already using Spring. In that case using SpringData and JPA instead of Hibernate-specific stuff would be much easier. Otherwise you can't really get rid of the warning because you can't change the api.

Upvotes: 1

Related Questions