首先,我认为我的问题表达得很糟糕,但我真的不知道该如何表达。
我有一个由许多类实现的启动接口。我想要做的是看看是否有一种方法可以创建一个新对象,以便向我传递泛型接口,然后根据.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...
}
}
}任何帮助都是非常感谢的!
发布于 2019-12-01 20:10:01
您可以使用反射来实现这一点:
public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}发布于 2019-12-01 20:27:12
这是许多解决方案中的一个常见问题。当我面对它时,我从不使用反射,因为如果它是一个大项目的一部分,那么它很难维护。
通常,当您必须根据用户选择构建对象时,就会出现此问题。为此,您可以尝试使用Decorator模式。因此,不是为每个选项构建不同的对象。您可以构建单个对象,并根据选择添加功能。例如:
// you have
Pizza defaultPizza = new BoringPizza();
// user add some ingredients
Pizza commonPizza = new WithCheese(defaultPizza);
// more interesting pizza
Pizza myFavorite = new WithMushroom(commonPizza);
// and so on ...
// then, when the user checks the ingredients, he will see what he ordered:
pizza.ingredients();
// this should show cheese, mushroom, etc.在引擎盖下:
class WithMushroom implements Pizza {
private final Pizza decorated;
public WithMushroom(Pizza decorated) {
this.decorated = decorated;
}
@Override
public Lizt<String> ingredients() {
List<String> pizzaIngredients = this.decorated.ingredients();
// add the new ingredient
pizzaIngredients.add("Mushroom");
// return the ingredients with the new one
return pizzaIngredients;
}
}关键是,您并不是为每个选项创建对象。相反,您可以创建具有所需功能的单个对象。每个装饰器都封装了一个功能。
https://stackoverflow.com/questions/59125310
复制相似问题