[英]instantiate class only given the class name as string from JComboBox
我有一个JComboBox,用户可以从94个不同的选项中进行选择,这些选项由字符串表示,对应于94个不同的类。
所有94个类都继承自一个称为AbstractTiling的父类。 选择这些选项之一(ComboBox中的字符串)后,应实例化所选的类。 但是由于有94种不同的可能性,所以我不想使用94 if语句。 因此,我使用了哈希图进行了尝试,但这导致了一个问题,即我仍然不知道要实例化的确切类型,因此我无法使用该类从父类覆盖的方法或让该父类覆盖的方法班没有。
在代码示例中,作为示例,hasmap中只有两个条目。 这是代码:
JComboBox groupscb = new JComboBox(isohedrals);
groupscb.setSelectedIndex(52);
groupscb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int selectedItem = ((JComboBox)arg0.getSource()).getSelectedIndex();
Map <Integer, Object> hm = new HashMap<Integer, Object>();
hm.put(52, new IH52());
hm.put(55, new IH55());
//here I want to instantiate the class, since I don't know it
//I used the parent class. But this keeps me from using the
//child classes methods
AbstractTiling tiling = (AbstractTiling) hm.get(selectedItem);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.