我很難創建CodeService接口的實現類。如何將類類型用作映射鍵和類的值列表作爲映射值?
public interface CodeService<T extends AbstractCode> {
Map<Class<T>, List<T>> getCodes();
}
AbstractCode是我的國家,城市和它在我的數據庫中的相應表名性別類的抽象超類。
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>)
我的問題是,我怎麼能存儲類類型作爲關鍵的IM我的地圖,這樣我可以獲取這個類的所有值的列表?
對於這是值得的,這是一個有趣的仿製藥練習,但作爲一個實際操作,至少是非常有問題的。 – chrylis