我在下面的代码中编写了以下GenericDAO

abstract public class DAO <T extends AbstractBusinessObject> {

// CRUD: create, read, update, delete

public abstract T create(Class<T> abObj);

public abstract T read();

public abstract void update(T abObj);

public abstract void delete(T abObj);
}


我还通过命令模式实现了一些命令,这些命令与扩展GenericDAO的DAOInMemory进行交互,以执行“注册用户名密码”之类的任务。

public class RegisterUserCommand extends AbstractCommand {

public RegisterUserCommand() {
    ...
}

...
@Override
public void execute(String[] cmdArgs) {

        // class cast here
        User userObject = (User) daoInstance.create(User.class);

        //why doesn't this work?
        //User userObject = daoInstance.create(User.class);

    }
}}


我不明白为什么DAOInMemory已经使用daoInstance.create(User.class)方法强制转换了create的结果?

public class DAOInMemory<T extends AbstractBusinessObject> extends DAO<T> {
    ...

public DAOInMemory() {
    ...


public T create(Class<T> abstractObjectType) {

    IDGenerator IDGenerator = IDGenerator.getInstance();

    if (User.class.isAssignableFrom(abstractObjectType)) {
        BigInteger id = IDGenerator.getID();
        User user = new User(id);
        return (T) user;
    }


您能解释一下Java的这种行为吗?

编辑:我忘了添加public class User extends AbstractBusinessObject

最佳答案

实例化DAO类时,必须避免使用泛型。

示例1 :(需要强制转换):

DAO dao = new DAOInMemory();
User user = (User) dao.create(User.class);


示例2 :(不需要强制转换):

DAO<User> dao = new DAOInMemory<User>();
User user = dao.create(User.class);

10-07 15:17