简体   繁体   中英

How generic DAO can return same type for all different DAO implementations?

I'm creating generic DAO for my DataNucleus JDO DAOs. Generic DAO will do get, update, delete, create operations and some other generic operations, so those implementations can be just extended in more specific DAOs.

Is it possible to somehow extend generic DAO and have it return correct types when for example get object by id?

User user = userDao.get(userId); // Is this possible when UserDao extends generic DAO ?? userDao should return user of type User instead of object.

Yes, it is possible to do this with generics:

public abstract class Dao<T> {
    public T get(String id) { ... }

    ...
}

public class UserDao extends Dao<User> {
    ...
}

UserDao userDao = new UserDao();
User user = userDao.get(userId); //Returns a User

Depending on your needs, Dao<T> can be an abstract base class, or a generic interface (eg public interface IDao<T> { ... }

Part of your question has already been answered by verdesmarald. I would like to add one important change in verdesmarald's code

You should prefer composition over inheritance. Instead of extending UserDao from Dao, UserDao should have a Dao. This way, your code will not be bound to a single implementation and mocking the Dao during unit testing will be possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM