javatar
javatar

Reputation: 33

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

Upvotes: 3

Views: 1093

Answers (4)

Luigi Plinge
Luigi Plinge

Reputation: 51109

Surely you just need

Hashtable<String, AbstractRestCommand>

Upvotes: 1

dynamic
dynamic

Reputation: 48131

Try:

Hashtable<string, Object>

Edit:

After reading your edit you can just do:

Hashtable<String, AbstractRestCommand>

Upvotes: 1

x4u
x4u

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

RonK
RonK

Reputation: 9652

I think you meant:

Hashtable<String, ? extends AbstractRestCommand>

Upvotes: 1

Related Questions