the*_*sti 2 java oop dictionary class first-class
我希望能够根据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"
Run Code Online (Sandbox Code Playgroud)
但我强烈怀疑这在Java中不起作用.
我的情况:我想创建一种将String名称与类相关联的方法.
用户可以使用其"名称"创建类的实例.
我想尝试:为类创建一个名称映射(我不知道如何在地图中存储类),并从地图中获取与"name"匹配的项目,然后实例化它.
那不行.
如何将类与String名称关联,并使用我给出的"名称"来实例化这些类?
您可以使用Supplier函数接口和对默认构造函数的方法引用:
Map<String, Supplier<Interface>> associations = new HashMap<>();
associations.put("first", One::new);
associations.put("second", Two::new);
Run Code Online (Sandbox Code Playgroud)
要实例化一个新对象,请调用Supplier.get:
Interface foo = associations.get("first").get();
Run Code Online (Sandbox Code Playgroud)
如果构造函数需要参数,则需要使用其他功能接口.对于单参数和双参数构造函数,您可以分别使用Function和BiFunction.还有更多,您需要定义自己的功能界面.假设构造函数都接受一个字符串,你可以这样做:
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);
Run Code Online (Sandbox Code Playgroud)
然后Function.apply用来获取实例:
Interface a = associations.get("first").apply("some string");
Run Code Online (Sandbox Code Playgroud)
如果你的构造函数使用不同数量的参数,那么你运气不好.