2011-05-30 94 views
3

我尝试实现相当于Java使用typeof(SomeClass的)

Hashtable<string, -Typeof one Class-> 
在Java中

。但我不知道如何使这个工作。我试过

Hashtable<String, AbstractRestCommand.class> 

但这似乎是错误的。

Btw。我希望这在运行时为每个反射创建一个新的类实例。

所以我的问题是,如何做这种东西。

编辑:

我有抽象类 “AbstractRestCommand”。现在我想创建有很多命令的哈希表是这样的:

 Commands.put("PUT", -PutCommand-); 
    Commands.put("DELETE", -DeleteCommand-); 

其中PutCommand和DeleteCommand延伸AbstractRestCommand,这样我就可以用

String com = "PUT" 
AbstractRestCommand command = Commands[com].forName().newInstance(); 
... 
+1

你的意思'哈希表<字符串,AbstractRestCommand>'? – BalusC 2011-05-30 20:56:33

回答

4

你想创建一个字符串一类的映射?这是可以做到这样:

Map<String, Class<?>> map = new HashMap<String, Class<?>>(); 
map.put("foo", AbstractRestCommand.class); 

如果你要限制的限制可能的类型有一定的接口或公用的超类,你可以使用绑定的通配符以后将允许您使用映射的类对象创建该类型的对象:

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

正是我所寻找的,thx – javatar 2011-05-30 21:11:55

+1

如果你所有的命令扩展了AbstractRestCommand,你只需要做一个简单的操作:'Hashtable '所有这些代码完全是冗余的 – dynamic 2011-05-30 21:15:17

+0

@ yes123:一个Class对象是有意义的,也就是说,如果你希望能够并行执行多个实例。即使命令本身是无状态的,它仍然可以更方便地让实现具有临时状态。 – x4u 2011-05-30 21:23:50

1

创建一个新的实例,我认为你的意思是:

Hashtable<String, ? extends AbstractRestCommand> 
1

尝试:

Hashtable<string, Object> 

编辑:

阅读你的编辑后,你可以这样做:

Hashtable<String, AbstractRestCommand> 
+0

这似乎已经过时了.. – Jack 2011-05-30 21:05:57

+0

如果它的作品,它更容易理解和doens't拍摄警告为什么不使用? – dynamic 2011-05-30 21:07:15

+0

我想使用强烈的打字... – javatar 2011-05-30 21:08:36

1

当然,你只需要

Hashtable<String, AbstractRestCommand>