Avoiding unchecked casting using generics

menteith :

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

Jacob G. :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71382&siteId=1