Reputation: 397
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
@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;
}
}
Upvotes: 14
Views: 22128
Reputation: 6364
Please don't use @SuppressWarnings
and 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
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;
}
Upvotes: 8
Reputation: 414
You can sure use TypedQuery with the parameter types is String in this case. So what you need is
TypedQuery<String> query = getEntityManager().createQuery(queryString, String.class);
Upvotes: 7
Reputation: 21975
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
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;
}
Upvotes: 2
Reputation: 26961
You will get this warning due runtime check cast.
Even if you use if(query.getResultList() instanceof List<?>)
you will get this warning, so...
@SuppressWarnings("unchecked")
orUpvotes: 4