lukaszrys
lukaszrys

Reputation: 1786

How to override method with method that has different type?

I have two classes

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;
    }
}

And i want to override (or just create) method in GenericDao with method from GenericDaoWIthObjectId. The problem occurs because as i read JVM "think" that List<Long> and List<Object> and probably Map<Long,T> and Map<Object,T> is the same. How can I make it work?

Upvotes: 0

Views: 72

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

As you've noticed, you can't overload a method solely by type parameter; i.e., if two method signatures differ only by type parameters, they're considered the same method. This is because of Java's implementation of generics by erasure -- methods are stripped of their type parameters when they're compiled, so they would actually become the same method.

You can do this either by adding additional parameters to differentiate the two, or by changing the name of one of the methods; these are the only alternatives.

Upvotes: 1

Related Questions