如何将类类型用作映射键,并将类的值列表用作映射值?

时间:2016-11-12 21:03:33

标签: java hibernate dictionary

我在创建CodeService接口的实现类时遇到了困难。

public interface CodeService<T extends AbstractCode> {
    Map<Class<T>, List<T>> getCodes();
}

AbstractCode是我的Country,City和Sex类的抽象超类,它在我的数据库中有相应的表名。

getCodes()方法应该返回类类型的地图作为键(Country.class,City.class,Sex.class)以及数据库返回的所有国家,城市和性别的列表。值。

我对getCodes()方法的实现如下:

public class HibernateCodeService<T extends AbstractCode> implements CodeService<T> {
    private Map<Class<T>, List<T>> map = new HashMap<Class<T>, List<T>>();

    public Map<Class<T>, List<T>> getCodes() {

        /* Create an instance of the HibernateCodeDao<Sex> class */
        CodeDao<Sex> sexDao = new HibernateCodeDao<Sex>();

        /* Set the class type as Sex.class */
        Class<Sex> type = Sex.class;

        /* Fetch all the sex values from the database */
        List<Sex> list = sexDao.fetchAll(Sex.class);

        /* Put the Sex.class as the map key, list of sexes as the value */
        map.put(type, list);

        /* Same code for Country and City classes */

        return map;
    }
}

但是,IDE会在map.put(type, list)行上发出错误。

put (java.lang.Class<T>, java.util.List<T>) in Map cannot be applied to (java.lang.Class<Sex>, java.util.List<Sex>)

我的问题是,如何将类类型存储为我的地图中的键,以便我可以获取此类的所有值的列表?

1 个答案:

答案 0 :(得分:1)

如果我要实例化HibernateCodeService<Country>的实例,那么您的地图将通过您的参数成为Map<Class<Country>, List<Country>>。由于CountrySex不相关,这意味着不允许将其插入地图。

现在,对于你想要完成的事情,你对泛型的使用是行不通的。因为地图的关键是Class<T>,这意味着您的地图每个实例只能包含一个可能的值,这有点会违背地图的目的。虽然我同意@chrylis认为这在生产系统中不是一件好事,但是你可以通过从界面中删除泛型来完成你想要完成的任务,并让你的方法返回:

public interface CodeService {
    Map<Class<? extends AbstractCode>, List<? extends AbstractCode>> getCodes();
}
相关问题