我希望能够根据HashMap
条目创建类的实例。
例如,这就是我会尝试从头顶写下的内容:
public class One implements Interface {
public void sayName() {
System.out.println("One");
}
}
public class Two implements Interface {
public void sayName() {
System.out.println("Two");
}
}
Map<String, Interface> associations = new HashMap<String, Interface>();
associations.put("first", One);
associations.put("second", Two);
Interface instance = new associations.get("first")();
instance.sayName(); // outputs "One"
但我强烈怀疑这在 Java 中不起作用。
我的情况:我想创建一种将String
名称与类关联的方法。
用户可以通过使用其“名称”来创建类的实例。
我想尝试:制作名称到类的映射(我不知道如何在映射中存储类),并从映射中获取与“名称”匹配的项目,然后实例化它。
那是行不通的。
如何将类与String
名称相关联并使用我给它的“名称”实例化这些类?