在不知道类名称的情况下调用构造函数(java)

在不知道类名称的情况下调用构造函数(java),java,class,constructor,Java,Class,Constructor,使用代码比使用文字更容易理解此问题: Map<Integer, Parent> objectMap = new HashMap<Integer, Parent>(); Parent myParent; Child1 myChild1; Child2 myChild2; //A lot more myChilds objectMap.put(1, myChild1); objectMap.put(2, myChild2); //Place all the myChild

使用代码比使用文字更容易理解此问题:

Map<Integer, Parent> objectMap = new HashMap<Integer, Parent>();

Parent myParent;
Child1 myChild1;
Child2 myChild2;
//A lot more myChilds

objectMap.put(1, myChild1);
objectMap.put(2, myChild2);
//Place all the myChilds

myChild1 = new Child1();  //Constructor is expensive, object may not get used
myChild2 = new Child2();  //Constructor is expensive, object may not get used
//Call constructor for all of myChilds

Parent finalObject;

int number = 1; //This can be any number

finalObject = objectMap.get(number);
在最后一行

有什么想法吗

提前谢谢


编辑:我想知道的是如何在不知道类名称的情况下调用构造函数。检查更新的代码。

不要同时构造两个对象。只构造你需要的对象

Parent finalObject;
if (condition) {
    finalObject = new Child1();
} else {
    finalObject = new Child2();
}

不要同时构造两个对象。只构造你需要的对象

Parent finalObject;
if (condition) {
    finalObject = new Child1();
} else {
    finalObject = new Child2();
}
这个怎么样

Parent finalObject;

if (condition) {
    finalObject = new Child1();
} else {
    finalObject = new Child2();
}
或者,更好的是,这个

Parent finalObject = condition? new Child1() : new Child2();
这个怎么样

Parent finalObject;

if (condition) {
    finalObject = new Child1();
} else {
    finalObject = new Child2();
}
或者,更好的是,这个

Parent finalObject = condition? new Child1() : new Child2();

您应该使用factory模式:

public interface Factory<T> {
  T create();
}
公共接口工厂{
T create();
}

工厂;
如果(条件){
工厂=工厂1;
}否则{
工厂=工厂2;
}
object=factory.create()

您应该使用出厂模式:

public interface Factory<T> {
  T create();
}
公共接口工厂{
T create();
}

工厂;
如果(条件){
工厂=工厂1;
}否则{
工厂=工厂2;
}
object=factory.create()

首先检查您的条件,然后在if或else语句中调用构造函数。 如果(条件) finalobject=newmychild1(); 其他的
finalobject=newmychild2()

首先检查您的条件,然后在if或else语句中调用构造函数。 如果(条件) finalobject=newmychild1(); 其他的
finalobject=newmychild2()

虽然这是可行的,但在这种情况下,这不是太过了吗?是的,很明显。我回答了一个更一般的问题!如果您想最小化了解所有可在此处构造的不同类的代码区域,这是一个好主意。虽然这样做可行,但在这种情况下,这不太可能是过分的吗?是的,很明显。我回答了一个更一般的问题!如果您想最小化代码区域(了解此处可以构造的所有不同类),这是一个好主意。请检查更新的代码。我无法预先知道是“myChild1”还是“myChild2”,请检查更新的代码。我无法提前知道是“myChild1”还是“myChild2”