Reputation: 33
I try to implement a
Hashtable<string, -Typeof one Class->
in Java. But I don't have an idea of how to get this working. I tried
Hashtable<String, AbstractRestCommand.class>
but this seems to be wrong.
Btw. I want this to create a new instance of the class per reflection at runtime.
So my question is, how to do this kind of stuff.
Edit:
I have the abstract Class "AbstractRestCommand". Now I would like to create a Hashtable with many commands like this:
Commands.put("PUT", -PutCommand-);
Commands.put("DELETE", -DeleteCommand-);
where PutCommand and DeleteCommand extends AbstractRestCommand, so that I can create a new instance with
String com = "PUT"
AbstractRestCommand command = Commands[com].forName().newInstance();
...
Upvotes: 3
Views: 1093
Reputation: 48131
Try:
Hashtable<string, Object>
Edit:
After reading your edit you can just do:
Hashtable<String, AbstractRestCommand>
Upvotes: 1
Reputation: 14077
Do you want to create a mapping of a string to a class? This can be done this way:
Map<String, Class<?>> map = new HashMap<String, Class<?>>();
map.put("foo", AbstractRestCommand.class);
If you want to restrict the restrict the possible types to a certain interface or common super class you can use a bounded wildcard which would later allow you to use the mapped class objects to create objects of that type:
Map<String, Class<? extends AbstractRestCommand>> map =
new HashMap<String, Class<? extends AbstractRestCommand>>();
map.put("PUT", PutCommand.class);
map.put("DELETE", DeleteCommand.class);
...
Class<? extends AbstractRestCommand> cmdType = map.get(cmdName);
if(cmdType != null)
{
AbstractRestCommand command = cmdType.newInstance();
if(command != null)
command.execute();
}
Upvotes: 4