简体   繁体   English

Java 等效于 typeof(SomeClass)

[英]Java equivalent of typeof(SomeClass)

I try to implement a我尝试实现一个

Hashtable<string, -Typeof one Class-> 

in Java.在 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.我希望它在运行时为每个反射创建一个 class 的新实例。

So my question is, how to do this kind of stuff.所以我的问题是,如何做这种事情。

Edit:编辑:

I have the abstract Class "AbstractRestCommand".我有抽象的 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其中 PutCommand 和 DeleteCommand 扩展了 AbstractRestCommand,以便我可以创建一个新实例

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

Do you want to create a mapping of a string to a class?是否要创建字符串到 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:如果您想将可能的类型限制为某个接口或常见的超级 class 您可以使用有界通配符,稍后您可以使用映射的 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();
}

I think you meant:我想你的意思是:

Hashtable<String, ? extends AbstractRestCommand>

Try:尝试:

Hashtable<string, Object>

Edit:编辑:

After reading your edit you can just do:阅读您的编辑后,您可以执行以下操作:

Hashtable<String, AbstractRestCommand>

Surely you just need当然你只需要

Hashtable<String, AbstractRestCommand>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM