2011-05-30 96 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>