Dynamic object creation with HashMap
        Posted  
        
            by 
                Salor
            
        on Game Development
        
        See other posts from Game Development
        
            or by Salor
        
        
        
        Published on 2014-08-20T13:58:35Z
        Indexed on 
            2014/08/20
            16:37 UTC
        
        
        Read the original article
        Hit count: 212
        
java
I want to use a HashMap to dynamically create objects based on the key.
I have a Random Map Generator that stores the maps in 3D Arrays of Type Integer[][][]. Upon creation of the actual map I iterate through this array and based on the Integer I want to create the right block.
Example: Integer[][][] map ... map[6][6][6] = 3; 3 is a Earth-Block and now I want to initialize a new Block of this type and give it the right coordinates.
Currently I store my Bindings from Integer to Class in a HashMap(Integer, String) and create my objects like that:
int id = array[x][y][z];
String block_name = Blocks.map.get(id);
Block block = (Block) Class.forName(block_name).newInstance();
block.setPosition(x,y,z);
But I want to avoid newInstance() if possible.
I've never worked that dynamically with Java before and I couldn't find a solution like changing the HashMap to (Integer, Class) or something. I just need to create a new Object based upon the Integer.
Any ideas/solutions? Thanks in advance and have a wonderful day!
© Game Development or respective owner