Java中typeof(SomeClass)的等效写法

3
我尝试实现一个
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();
...

1
你是指 Hashtable<String, AbstractRestCommand> 吗? - BalusC
4个回答

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

1
如果您的所有命令都扩展了AbstractRestCommand,那么您只需要执行简单操作:Hashtable<String, AbstractRestCommand>。所有这些代码都是完全冗余的。 - dynamic
@yes123:将映射到类对象可以很有意义,例如如果您想要能够并行执行多个实例。即使命令本身是无状态的,允许实现具有临时状态仍然可能更方便。 - x4u

1

我想你的意思是:

Hashtable<String, ? extends AbstractRestCommand>

1

尝试:

Hashtable<string, Object>

编辑:

阅读您的编辑后,您只需执行以下操作:

Hashtable<String, AbstractRestCommand>

如果它能够正常工作且更易于理解,且不会发出警告信息,为什么不使用呢? - dynamic
它强制将地图值向下转换为任何操作,这会打破类型安全原则,从那一点上移除类型检查,因此在任何情况下都不好。 - Jack

1

你只需要这个

Hashtable<String, AbstractRestCommand>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接