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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…