0

我有两节课

GenericDaoWithObjectId.class

public abstract class GenericDaoWithObjectId<T extends IEntity, Z extends Serializable> extends GenericDao<T> {
    public Map<Object, T> findByIdsAsMap(List<Object> ids, boolean addNonDeletedConstraint) throws DaoException {
        String query = addNonDeletedConstraint ? QUERY_FIND_NON_DELETED_BY_IDS : QUERY_FIND_BY_IDS;
        query = query.replaceAll("\\{type\\}", type);
        Query q = getSession().createQuery(query);
        q.setParameterList("ids", ids);
        List<T> entities = (List<T>) q.list();
        if (entities.size() != ids.size()) {
            throw new DaoException(DaoErrorCodes.OBJECT_NOT_FOUND);
        }
        Map<Object, T> result = new HashMap<Object, T>(); // I would've done that in query (using SELECT new map(u.id, u), but hibernate has a bug...
        // (https://hibernate.onjira.com/browse/HHH-3345)
        for (T e : entities) {
            result.put(e.getId(), e);
        }
        return result;
    }
}

GenericDao.class

public abstract class GenericDao<T extends IEntity> {
    public Map<Long, T> findByIdsAsMap(List<Long> ids, boolean addNonDeletedConstraint) throws DaoException {
        String query = addNonDeletedConstraint ? QUERY_FIND_NON_DELETED_BY_IDS : QUERY_FIND_BY_IDS;
        query = query.replaceAll("\\{type\\}", type);
        Query q = getSession().createQuery(query);
        q.setParameterList("ids", ids);
        List<T> entities = (List<T>) q.list();
        if (entities.size() != ids.size()) {
            throw new DaoException(DaoErrorCodes.OBJECT_NOT_FOUND);
        }
        Map<Long, T> result = new HashMap<Long, T>(); // I would've done that in query (using SELECT new map(u.id, u), but hibernate has a bug...
                                                      // (https://hibernate.onjira.com/browse/HHH-3345)
        for (T e : entities) {
            result.put((Long) e.getId(), e);
        }
        return result;
    }
}

我想用来自 GenericDaoWIthObjectId 的方法覆盖(或只是创建)GenericDao 中的方法。出现问题是因为当我阅读 JVM 时“认为”List<Long>和 List<Object>并且可能Map<Long,T>Map<Object,T>相同。我怎样才能让它工作?

4

1 回答 1

1

正如您所注意到的,您不能仅通过类型参数重载方法;即,如果两个方法签名仅在类型参数上有所不同,则它们被认为是相同的方法。这是因为 Java 通过擦除实现了泛型——方法在编译时被剥离了它们的类型参数,因此它们实际上会变成相同的方法。

您可以通过添加额外的参数来区分两者,或者通过更改其中一个方法的名称来做到这一点;这些是唯一的选择。

于 2013-11-04T14:09:32.863 回答