如何基于接口实现创建新对象

时间:2019-12-01 12:02:23

标签: java interface instance implements

首先,我认为我的问题用词不好,但我并不真正理解该措词。

我有一个由多个类实现的启动接口。我想做的是查看是否有一种方法可以创建一个新对象,以使我被传递给通用接口,然后基于.getClass()。getSimpleName()方法,基于该字符串创建一个新对象。

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

参考代码:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

然后我将有我的实现类:

public interface MyInterface {
  public void someMethod();
}

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

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 }
}

我们非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您可以为此使用反射:

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

答案 1 :(得分:0)

这是许多解决方案中的常见问题。当我面对它时,我从不使用反射,因为如果它是大型项目的一部分,则很难维护。

通常,当您必须基于用户选择来构建对象时,就会出现此问题。您可以尝试使用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;
    }
}

重点是您没有为每个选项创建对象。相反,您将创建具有所需功能的单个对象。每个装饰器都封装一个功能。