0

I have a set of classes that implement a certain interface. I have put all those classes in a Hashtable ht like this:

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

But when I call the get() function of the hashtable and try to cast the object as the Interface's object, I am getting a ClassCastException:

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

How can I resolve the same? I have to call functions of the class but, I am not even able to cast properly? What is wrong in this?

3 Answers 3

3

Because you are putting a Class and you try to get an Interface4. If you want to have instances, rather than definitions inside the map, use: t.put(str, new ADC()). A few notes:

  • You can also use generics to guarantee that you put the correct things at compile time: Hashtable<String, Interface4>.
  • Prefer HashMap to Hashtable
Sign up to request clarification or add additional context in comments.

Comments

1

backend.instructions.ADC.class is a Class, not an instance of that class.

You can do

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

Comments

0

You have put the definition of the class in the table. You need to put actual instances of the class.

 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"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.