Java is equivalent to typeof (someclass)
•
Java
I try to achieve one
Hashtable<string,-Typeof one Class->
In Java But I don't know how to make this work I tried
Hashtable<String,AbstractRestCommand.class>
But this seems wrong
By the way I want this to create a new instance of the class for each reflection at run time
So my question is, how to do such a thing
Edit:
I have the abstract class "abstractrestcommand" Now I want to create a hashtable with many commands:
Commands.put("PUT",-PutCommand-); Commands.put("DELETE",-DeleteCommand-);
Putcommand and DeleteCommand extend abstractrestcommand so that I can use it to create a new instance
String com = "PUT" AbstractRestCommand command = Commands[com].forName().newInstance(); ...
Solution
Do you want to create a string to class mapping? This can be done by:
Map<String,Class<?>> map = new HashMap<String,Class<?>>(); map.put("foo",AbstractRestCommand.class);
If you want to limit the possible types to an interface or public superclass, you can use bounded wildcards. Later, you can use the mapped class object to create an object of this 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(); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码