我希望能够基于 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
名称关联起来,并使用我指定的“名称”实例化这些类?
最佳答案
您可以使用Supplier
功能接口(interface)和对默认构造函数的方法引用:
Map<String, Supplier<Interface>> associations = new HashMap<>();
associations.put("first", One::new);
associations.put("second", Two::new);
要实例化一个新对象,请调用 Supplier.get
:
Interface foo = associations.get("first").get();
<小时/>
如果您的构造函数需要参数,则需要使用另一个 functional interface 。对于一参数和二参数构造函数,您可以使用 Function
和 BiFunction
分别。如果再多,您将需要定义自己的功能接口(interface)。假设构造函数都采用字符串,您可以这样做:
class One implements Interface
{
One(String foo){ }
public void sayName() {
System.out.println("One");
}
}
Map<String, Function<String, Interface>> associations = new HashMap<>();
associations.put("first", One::new);
然后使用 Function.apply
获取实例:
Interface a = associations.get("first").apply("some string");
如果您的构造函数采用不同数量的参数,那么您就不走运了。
关于java - 将类存储在 Map 中以便可以实例化它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49697185/