Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding unchecked casting using generics

Tags:

java

generics

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").

like image 555
menteith Avatar asked Aug 03 '18 16:08

menteith


People also ask

How can I avoid unchecked cast warnings?

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.

What is suppress warning unchecked?

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.

What is unchecked assignment in Java?

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.


1 Answers

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);
like image 95
Jacob G. Avatar answered Sep 25 '22 11:09

Jacob G.