Tapas Bose
Tapas Bose

Reputation: 29816

Create List or Cast by List from Class name

I have generic class, and I want to create a List or cast by List. I only have the class type. What I want to get is:

public class CustomerDao extends BaseDao<Customer> implements ICustomerDao {

    private Class<Customer> entityClass;

    public CustomerDao(Class<Customer> entityClass) {
        super(entityClass);
        this.entityClass = entityClass;
    }

    public void getCustomers() {
        List<***> list = (List<***>)getSessionFactory().getCurrentSession().createCriteria(entityClass).list();
    }
}

Now how can I use the field entityClass to create the List<***> list? Is it possible?

I can use List<Customer> list = getSessionFactory().getCurrentSession().createCriteria(entityClass).list();, but I am want to learn different way.

Upvotes: 0

Views: 222

Answers (2)

Perception
Perception

Reputation: 80633

Seems you are trying to implement a type-specific DAO (for your Customer entity), derived from an abstract, generic Base DAO. If indeed that is what you are trying to accomplish then there is no need for generics at all:

public class CustomerDao extends BaseDao<Customer> implements ICustomerDao {

    public CustomerDao() {
        super(Customer.class);
    }

    public List<Customer> getCustomers() {
        final List<Customer> list = (List<Customer>) getSessionFactory().
            getCurrentSession()
           .createCriteria(Customer.class).list();
    }
}

Its been awhile since I used the Hibernate API's, but I dont think you need the typecast to List<Customer> either.

Upvotes: 2

SLaks
SLaks

Reputation: 887797

That would be meaningless.
Generics only exist at compile-time.

Instead, you should make your entire class generic.

Upvotes: 1

Related Questions