Reputation:
All APIs in Hibernate are from 1.4 and are thus not using java generics.
So I wonder how "safe" the following is: (preconditions: name column is of datatype String, or atleast compatible to String)
@SuppressWarnings("unchecked")
public List<String> getAll() {
Query q = session.createQuery(
"select name from Customers");
return q.list();
}
From the Queryi API (org.hibernate.Query.list()) javadoc.
Upvotes: 4
Views: 3704
Reputation: 122449
It'll be safe as long as you are sure that the query does not "contain multiple results per row". (I'm not familiar with queries, so I am unsure whether it can happen in this case.) If a row does contain multiple results, then when you try to access it, it will throw ClassCastException at runtime because that element will be an Object[] object instead of a String object.
Upvotes: 3
Reputation: 35151
Java generics use type erasure, so at runtime there's no difference between a List
, a List<String>
, and a List<Integer>
. All are really just List
s. At compilation, the compiler will enforce the template parameter type, but under the covers at runtime, you a have a List
.
In fact, if you try to use reflection to find the template parameter type, you can't.
Upvotes: 3
Reputation: 60190
In Java, generics actually are erasures, which is nothing but compiler magic. The types used as generic type arguments are unknown at runtime. Therefore, the cast should be successful if the list returned implements the List interface, but the compiler may throw warnings at you.
Upvotes: 2