Java等价于typeof(SomeClass)
发布时间:2020-12-15 08:40:53 所属栏目:Java 来源:网络整理
导读:我试着实现一个 Hashtablestring,-Typeof one Class- 在Java中.但我不知道如何让这个工作.我试过了 HashtableString,AbstractRestCommand.class 但这似乎是错误的. 顺便说一句.我希望这在运行时为每个反射创建一个类的新实例. 所以我的问题是,如何做这种事情
我试着实现一个
Hashtable<string,-Typeof one Class-> 在Java中.但我不知道如何让这个工作.我试过了 Hashtable<String,AbstractRestCommand.class> 但这似乎是错误的. 顺便说一句.我希望这在运行时为每个反射创建一个类的新实例. 所以我的问题是,如何做这种事情. 编辑: 我有抽象类“AbstractRestCommand”.现在我想用这样的许多命令创建一个Hashtable: 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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |