Java等价于typeofSomeClass

问题描述

| 我尝试实施
Hashtable<string,-Typeof one Class-> 
在Java中。但是我不知道如何使它工作。我试过了
Hashtable<String,Abstractrestcommand.class>
但这似乎是错误的。 顺便说一句。我希望它在运行时按反射创建类的新实例。 所以我的问题是,如何做这种事情。 编辑: 我有抽象类\“ Abstractrestcommand \”。现在,我想使用许多命令创建一个哈希表:
        Commands.put(\"PUT\",-PutCommand-);
    Commands.put(\"DELETE\",-DeleteCommand-);
PutCommand和DeleteCommand扩展了Abstractrestcommand的位置,因此我可以使用
String com = \"PUT\"
Abstractrestcommand command = Commands[com].forName().newInstance();
...
    

解决方法

        您是否要创建字符串到类的映射?这可以通过以下方式完成:
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();
}
    ,        我想你的意思是:
Hashtable<String,? extends AbstractRestCommand>
    ,        尝试:
Hashtable<string,Object>
编辑: 阅读您的修改后,您可以执行以下操作:
Hashtable<String,AbstractRestCommand>
    ,        当然,您只需要
Hashtable<String,AbstractRestCommand>