【发布时间】:2016-11-12 21:03:32
【问题描述】:
我在创建 CodeService 接口的实现类时遇到了困难。
public interface CodeService<T extends AbstractCode> {
Map<Class<T>, List<T>> getCodes();
}
AbstractCode 是我的 Country、City 和 Sex 类的抽象超类,它们在我的数据库中具有相应的表名。
getCodes() 方法应该返回一个类类型的地图作为键(Country.class、City.class、Sex.class),并返回数据库返回的所有国家、城市和性别的列表作为值。
我对@987654323@方法的实现如下:
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>)
我的问题是,如何将类类型存储为我的地图中的键,以便我可以获取该类的所有值的列表?
【问题讨论】:
-
对于它的价值,这是一个有趣的泛型练习,但至少在实际实践中是非常值得怀疑的。
标签: java hibernate dictionary