简体   繁体   English

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

[英]Calling the constructor without knowing the name of the class (java)

This problem easier to understand with code than with words: 用代码比用单词更容易理解这个问题:

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);

As you see, I don't know in advance which class will finalObject be. 如您所见,我事先不知道finalObject将是哪个类。 The code works without problem, but here is my question: 该代码可以正常工作,但这是我的问题:

How can I avoid calling both constructors? 如何避免同时调用两个构造函数?

As only myChild1 or myChild2 will be used and the constructor methods are quite expensive, I want to only call the one that will actually get used. 由于将仅使用myChild1或myChild2并且构造方法非常昂贵,因此我只想调用将实际使用的方法。

Something like 就像是

finalObject.callConstructor();

in the last line 在最后一行

Any ideas? 有任何想法吗?

Thanks in advance. 提前致谢。

EDIT: What I want to know is how to call the constructor without knowing the name of the class . 编辑:我想知道的是如何在不知道类名的情况下调用构造函数。 Check the updated code. 检查更新的代码。

How about this? 这个怎么样?

Parent finalObject;

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

Or, even better, this? 或者,甚至更好?

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

Don't construct both objects. 不要同时构造两个对象。 Only construct the object you need. 只构造您需要的对象。

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

You should use the factory pattern : 您应该使用工厂模式:

public interface Factory<T> {
  T create();
}

... ...

Factory<T> factory;
if (condition) {
  factory = FACTORY1;
} else {
  factory = FACTORY2;
}
object = factory.create()

First check your condition and then inside the if or else statement call the constructor. 首先检查条件,然后在if或else语句中调用构造函数。 if(condition) finalobject = new myChild1(); if(condition)finalobject = new myChild1(); else finalobject = new myChild2(); 否则finalobject = new myChild2();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM