How to create a new object based on interface implementation

Mariosyian :

Firstly, I believe my question is badly worded but don't really understand how to phrase it.

I have a starting interface that is being implemented by a number of classes. What I want to do is to see if there is a way to create a new object such that I am being passed the generic interface, then based on the method .getClass().getSimpleName(), create a new object based on that string.

Is the only way to create a switch case statement? As the number of implementing classes are too many (about 100 or so).

Reference code:

public interface MyInterface {
  public void someMethod();
}

then I would have my implementing classes:

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

What I want to have in the end is another class which is passed an argument of type MyInterface, get the simple name from that and create a new instance of MyClassX based on that simple name.

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

Any help is highly appreciated!

Mark Bramnik :

You can use reflection for this:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357740&siteId=1