Using a @SupressWarning everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call q.list().
There are two other techniques I'd suggest:
Collections.checkedList()
Replace your assignment with this:
List<Cat> cats = Collections.checkedList(Cat.class, q.list());
You might want to check the the javadoc for that method, especially with regards to equals() and hashCode().
Write a cast-helper
Simply refactor all your @SupressWarnings into one place:
List<Cat> cats = MyHibernateUtils.listAndCast(q);
...
public static <T> List<T> listAndCast(Query q) {
@SuppressWarnings("unchecked")
List list = q.list();
return list;
}
Some comments:
- I chose to pass in the Query instead of the result of q.list() because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any List in general.
- You could add similar methods for .iterate() etc.