使用java泛型的继承不能按预期工作

时间:2017-01-04 08:48:13

标签: java generics inheritance

我正在尝试使用继承和泛型来创建我的应用程序,但它似乎不像我期望的那样工作。我会告诉你我的意思(TL; DR在底部):

public interface IModel extends Serializable {
    public int save();
    public void update();
    public void delete();
}

// <T> is a JPA annotated entity/class
@SuppressWarnings("serial")
public abstract class Model<T> implements IModel {
    private final Repository<T> _repository;
    protected T _entity;

    public Model(T entity, Repository<T> repository) {
        this._entity = entity;
        this._repository = repository;
    }

    public int save() {
        return _repository.save(_entity);
    }
    ...
}

这是在我的AccountModel中实现的,这是一个具有通用Account的模型(它是一个JPA实体),它实现了IAccount。

public class AccountModel extends Model<Account> implements IAccount {
    private static final AccountRepository REPOSITORY = new AccountRepository();

    public AccountModel(Account entity) {
        super(entity, REPOSITORY);
    }
    // Method implementations...
}

我的通用Repository如下所示:

public abstract class Repository<T> implements Serializable {

    private static SessionFactory SESSION_FACTORY;
    private final Class<T> _repositoryClass;
    private static boolean _initiated = false;

    public Repository(Class<T> repositoryClass) {

        if (!Repository._initiated) 
            setup();

        this._repositoryClass = repositoryClass;
    }

    private void setup() {
        // logics
        Repository._initiated = true;
    }

    public final Model<T> getById(int id) {

        Session session = SESSION_FACTORY.openSession();

        try {
            session.beginTransaction();
            T t = session.get(_repositoryClass, id);
            return new Model<T>(t, this); // As suggested by @Vlad
        }
        finally {
            session.close();
        }
    }
}

此抽象存储库的帐户实现是:

public class AccountRepository extends Repository<Account> {

    public AccountRepository() {
        super(Account.class);
    }

    public Model<Account> getByEmail(String emailAddress) {...}
}

到目前为止一切顺利,这一切都按预期工作。但我不能将Model<T>用作TModel

TL; DR

我想使用以下代码行:
AccountModel account = new AccountRepository().getById(1);
由于AccountModel继承Model<Account>new AccountRepository().getById()始终返回Model<Account>,我希望此功能正常运行,但事实并非如此。

我错过了什么?

0 个答案:

没有答案