0

I have a hashmap defined as the following

    Map<Class, Object> runners = new HashMap<Class, Object>();
    runners.put(Entity.class, new EntityRunner());

In a function I get passed an element that contains a method getClass().

this class corresponds to a key in the hash map defined above.

What I want to do is be able to get the corresponding Object from the hash map, assign it to a variable, and then cast it to the corresponding object and be able to execute that objects methods

Any ideas?

mwild
  • 1,483
  • 7
  • 21
  • 41
  • 1
    Casting will not be useful for this, since you don't know the type you want to cast to at compile time. You could use reflection. – Jesper Jan 07 '16 at 09:54
  • Take a look at http://stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-variable-from-one-type-to-another – stevops Jan 07 '16 at 09:59
  • So you want to do `auto obj = map.get(someClass); obj.method();` (hypothetical syntax)? You might want to rethink your design if you have to do this. – dhke Jan 07 '16 at 10:04
  • Reflection worked a treat, thanks @Jesper – mwild Jan 07 '16 at 10:56

2 Answers2

1

Well, use the cast operator.

EntityRunner runner = (EntityRunner)runners.get(Entity.class)

More seriously, you have a design smell here. How do you know what class to cast to? If you cannot write it verbatim in the code you will have problems writing method calls.

Or you could use reflexion, but that is just pushing the problem further: even then how do you know which method to call?

cadrian
  • 7,332
  • 2
  • 33
  • 42
0

I don't see anything difficulty here.

you can try below

import java.util.HashMap;
import java.util.Map;


public class TestClass {
     public static void main(String []args){
         Map<Class, Object> runners = new HashMap<Class, Object>();
         runners.put(TestClass.class, new TestClass());
         // getting TestClass instance from map
         TestClass obj = (TestClass) runners.get(TestClass.class);
         obj.display();

         //It is as good as using HashMap without Generics
         Map runners2 = new HashMap();
         runners2.put(TestClass.class, new TestClass());
         obj = (TestClass) runners.get(TestClass.class);
         obj.display();

     }

    public void display(){
        System.out.println("In DisplayMethod");
    }
}

However it is not Recommended to use the DataTypes like Object/Class for Key/Value pair. You never know where you will get ClassCastException .

This was the main reason Generics was introduced in Java.

Shirishkumar Bari
  • 2,692
  • 1
  • 28
  • 36