VWeber
VWeber

Reputation: 1261

Cast list of interfaces to list of concrete type

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

Answers (4)

tmarwen
tmarwen

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

ControlAltDel
ControlAltDel

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

Rohit Jain
Rohit Jain

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

StackFlowed
StackFlowed

Reputation: 6816

Use this type of code.

List<? extends yourParentClass> 

Upvotes: 1

Related Questions