Mikhail.Mamaev
Mikhail.Mamaev

Reputation: 8039

How to convert list type in Java hibernate

In java application I use hibernate criteria queries, for example:

Criteria criteria = session.createCriteria(Any.class);
...

List<?> list = criteria.list();

and I definetly know that result list contains only objects of type Any but I don't know if it's possible to get list of type defined above?

In this case, if I want to use foreach it's necessary to convert type from object to type Any

for(Object object : list) {
    ...
    ((Any)object).
    ...
}

Or if I need to get an array I have to do something like this:

list.toArray(new Any[]{});

Do you have any ideas?

Upvotes: 1

Views: 3023

Answers (1)

Thomas Jung
Thomas Jung

Reputation: 33092

Hibernate does not support generics. So the following code is the "best" you get:

@SuppressWarnings("unchecked")
List<Any> resultList = criteria.list();

for(Any any : resultList){ ... }

Maybe

List<Any> resultList = criteria.list();
for(Any any : resultList){ ... }

is better as the type warning is still there. This convertion cannot be checked by the compiler. So the warning is ok.

Upvotes: 3

Related Questions