I wanted to learn something more about generics and to do so I decided to write a simple application. It allows to retrieve list of all entities using CriteriaQuery
.
First of all, I tried to generify code by using type parameter
(T). However, my code will not even compile. Why?
private static <T> List<T> retrieveAllT(Session session,
CriteriaBuilder criteriaBuilder, T t) {
CriteriaQuery<t> query = criteriaBuilder.createQuery(t);
Root root = query.from(t);
query.select(root);
return session.createQuery(query).getResultList();
}
I've come up with another solution. It works fine, but the compiler informs me about unchecked casting. I understand the reason of that but I'd like to know whether is possible to write this piece of code in a more elegant way (i.e. without unchecked casting)? If so, how do I do that?
private static List<?> retrieveAll(Session session,
CriteriaBuilder criteriaBuilder, Class clazz) {
CriteriaQuery query = criteriaBuilder.createQuery(clazz);
Root root = query.from(clazz);
query.select(root);
return session.createQuery(query).getResultList();
}
To be sure, I am aware of @SuppressWarnings("unchecked")
.
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
In other words, it basically, tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
Unchecked assignment: 'java.util.List' to 'java.util.List<java.lang.String>' It means that you try to assign not type safe object to a type safe variable. If you are make sure that such assignment is type safe, you can disable the warning using @SuppressWarnings annotation, as in the following examples.
First of all, I tried to generify code by using type parameter (T). However, my code will not even compile. Why?
You are not allowed to parameterize a type with an instance of a class, but must use the type itself:
CriteriaQuery<t> query = criteriaBuilder.createQuery(t);
Needs to be changed to:
CriteriaQuery<T> query = criteriaBuilder.createQuery(t);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With