Reputation: 11
I'm stuck on a problem with creating a new instance from a stored class in an hashmap.
I'm doing : saving an instance of a class to a hashmap as referal to load classes from by UIN (unique item name) ((which is a string))
problem : the instance saved stays the same, resulting in placing the same instance for every block saved, which results in only one block being replaced when a save is loaded.
looking for : how would i create a new instance so i can place all my blocks properly back ?
Code :
Registering:
/*======================Registry===========================*/
public static HashMap<String, Block> registeredBlocks = new HashMap<String, Block>();
public static void registerBlock(Block block){
registeredBlocks.put(block.getUIN(), block);
}
public static void loadBlocks(){
registerBlock(new BlockChest());
registerBlock(new BlockTree());
System.out.println(registeredBlocks);
System.out.println(registeredBlocks.containsKey("chestBlock"));
System.out.println(registeredBlocks.get("chestBlock"));
System.out.println(Blocks.chest);
}
public static Block getBlockFromUIN(String uin){
if(registeredBlocks.containsKey(uin)){
return registeredBlocks.get(uin);
}
return null;
}
Reference
public static BlockChest chest = (BlockChest)Block.registeredBlocks.get("chestBlock");
public static BlockTree log = (BlockTree)Block.registeredBlocks.get("treeLog");
Upvotes: 0
Views: 2270
Reputation: 32680
You're not storing classes in your hashmap:
HashMap<String, Block> registeredBlocks
This is mapping Strings to Block
instances, hence the behavior you're observing.
Instead:
HashMap<String, Class> registeredBlocks
will store Class objects
registeredBlocks.put(block.getUIN(), block.getClass()); //or Block.class
will put the Block
class to your map with whatever the key String is, and
Block b = (Block)registeredBlocks.get(keyString).newInstance();
will give you a new instance of that class, cast to Block
.
Note 1: this is utilizing the Class.newInstance()
method.
Note 2: This is meant purely as an answer to your question. What you're trying to do is not immediately apparent in your post, but I'm fairly confident there's a cleaner/better way to achieve what you're trying to achieve.
Upvotes: 2