在不知道Java中类的名称的情况下调用类构造函数

在不知道Java中类的名称的情况下调用类构造函数,java,dictionary,Java,Dictionary,使用代码比使用文字更容易理解此问题: Map<Integer, Parent> objectMap = new HashMap<Integer, Parent>(); Parent myParent; Child1 myChild1; Child2 myChild2; //A lot more myChilds myChild1 = new Child1(); //Constructor is expensive, object may not get used m

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

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

Parent myParent;
Child1 myChild1;
Child2 myChild2;
//A lot more 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

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


Parent finalObject;

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

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

有什么想法吗


提前感谢。

您可以将子对象的构造函数设置为虚拟构造函数,然后创建另一个方法来执行实际的初始化,这是非常昂贵的


当您知道需要哪个孩子时,请调用此方法进行昂贵的初始化。

.class
存储在地图中,然后在需要时使用

final Map<Integer, Class<? extends Parent>> objectMap = new HashMap<>();
objectMap.put(1, Child1.class);
objectMap.put(2, Child2.class)
// ...

// then later
final Parent aChild1 = objectMap.get(1).newInstance()

final MapTry using google's cache(guava):看到这个教程了吗?这正是我想要的,但我得到了一个非法的AccessException(尽管我试图公开所有内容)和一个实例化Exception(但用“new”实例化它很好)。关于如何解决这个问题,你有什么想法吗?如果不留下一个stacktrace,很难说,也许你应该发布一个“后续”问题,并附上一个完整的
IllegalAccessException
final Map<Integer, Class<? extends Parent>> objectMap = new HashMap<>();
objectMap.put(1, Child1.class);
objectMap.put(2, Child2.class)
// ...

// then later
final Parent aChild1 = objectMap.get(1).newInstance()