如何用不同类型的方法覆盖方法?

时间:2013-11-04 14:02:55

标签: java

我有两个班级

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>和列表<Object>以及可能Map<Long,T>Map<Object,T>是相同的。我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:1)

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

您可以通过添加其他参数来区分两者,或者通过更改其中一个方法的名称来实现此目的;这些是唯一的选择。