gpt4 book ai didi

java - 如何根据接口(interface)实现创建新对象

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:07 25 4
gpt4 key购买 nike

首先,我认为我的问题措辞很糟糕,但我不太明白如何表达它。

我有一个由许多类实现的起始接口(interface)。我想做的是看看是否有一种方法可以创建一个新对象,以便我可以传递通用接口(interface),然后基于方法 .getClass().getSimpleName(),根据该字符串创建一个新对象。

这是创建 switch case 语句的唯一方法吗?由于实现类太多(大约100个左右)。

引用代码:

public interface MyInterface {
public void someMethod();
}

然后我会有我的实现类:

public class MyClass1 implements MyInterface {
public void someMethod() { //statements }
}

public class MyClass2 implements MyInterface {
public void someMethod() { //statements }
}

public class MyClass3 implements MyInterface {
public void someMethod() { //statements }
}

我最终想要的是另一个类,它传递一个 MyInterface 类型的参数,从中获取简单名称,并根据该简单名称创建一个新的 MyClassX 实例。

public class AnotherClass {
public void someMethod(MyInterface interface) {
if (interface == null) {
System.err.println("Invalid reference!");
System.exit(-1);
} else {
String interfaceName = interface.getClass().getSimpleName();
/**
* This is where my problem is!
*/
MyInterface newInterface = new <interfaceName> // where interfaceName would be MyClass1 or 2 or 3...
}
}
}

非常感谢任何帮助!

最佳答案

您可以为此使用反射:

public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}

关于java - 如何根据接口(interface)实现创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com