Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

java - 如何基于接口实现创建新对象(How to create a new object based on interface implementation)

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.

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

Is the only way to create a switch case statement?

(是创建switch case语句的唯一方法吗?)

As the number of implementing classes are too many (about 100 or so).

(由于实现类的数量太多(大约100个左右)。)

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.

(最后,我要提供的另一个类是传递给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...
    }
  }
}

Any help is highly appreciated!

(任何帮助深表感谢!)

  ask by Mariosyian translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...