简体   繁体   中英

Java equivalent of typeof(SomeClass)

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();
...

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();
}

I think you meant:

Hashtable<String, ? extends AbstractRestCommand>

Try:

Hashtable<string, Object>

Edit:

After reading your edit you can just do:

Hashtable<String, AbstractRestCommand>

Surely you just need

Hashtable<String, AbstractRestCommand>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM