Reputation: 1261
I have a method that get's some objects from a db:
public <T extends Persistable> List<T> getAllEntitiesEager(
Class clazz, String sortField, SortOrder sortOrder,
Map<String, Object> filters, boolean invalidate);
This method returns a list of objects from type clazz
. All objects returned implement the Interface Persistable
. Now I need a List of concrete types. Is this even possible?
Example:
The Class UserEntity
implements Persistable
and I want to do something like that:
List<UserEntity> userList = (List<UserEntity)
someObject.getAllEntitiesEager(UserEntity.class,...)
Upvotes: 1
Views: 2911
Reputation: 16374
You method signature should declare the generic class type Class<T> clazz
so the returned List
will be with from same class type:
public <T extends Persistable> List<T> getAllEntitiesEager(Class<T> clazz, String sortField, SortOrder sortOrder, Map<String, Object> filters, boolean invalidate);
And yes it is feasible :)
Upvotes: 2
Reputation: 35106
I think you can do this with autoboxing if you change Class clazz
to Class<T> clazz
... I don't have a development env to test this sorry
Upvotes: 0
Reputation: 213391
Why not just change the type of clazz
to Class<T>
?
public <T extends Persistable> List<T> getAllEntitiesEager(Class<T> clazz,
String sortField, SortOrder sortOrder,
Map<String, Object> filters, boolean invalidate);
With this, the returned list will be of same type as you pass the clazz
type.
Upvotes: 6