将类放在Hashtable中

时间:2011-08-31 06:15:54

标签: java interface hashtable

我有一组实现某个接口的类。我已将所有这些课程安排在Hashtable ht中,如下所示:

ht.put(str,backend.instructions.ADC.class);

但是当我调用哈希表的get()函数并尝试将对象转换为接口的对象时,我得到的是ClassCastException

           InsInterface4 obj=(InsInterface4) ht.get(str);

我该如何解决?我必须调用类的功能但是,我甚至无法正确投射?这有什么问题?

3 个答案:

答案 0 :(得分:3)

因为您要放置Class,并且您尝试获得Interface4。如果您想拥有实例,而不是地图中的定义,请使用:t.put(str, new ADC())。几点说明:

  • 您还可以使用泛型来保证在编译时放置正确的内容:Hashtable<String, Interface4>
  • 首选HashMapHashtable

答案 1 :(得分:1)

backend.instructions.ADC.class是一个类,而不是该类的实例。

你可以做到

Class<InsInterface4> clazz = (Class<InsInterface4>) ht.get(str);
// if there is a default constructor
InsInterface4 obj = (InsInterface4_ clazz.newInstance();

答案 2 :(得分:0)

您已将类的定义放在表中。您需要放置该类的实际实例。

 backend.instructions.ADC anAdc = new  backend.instructions.ADC();
 someOther.instructions.OTH anOth = new  someOther.instructions.OTH();

 ht.put("adc", anAdc);
 ht.put("oth", anOth);

 InsInterface4 obj=(InsInterface4) ht.get("adc");