简体   繁体   English

仅从JComboBox给出类名作为字符串的实例化类

[英]instantiate class only given the class name as string from JComboBox

I have a JComboBox where the user can choose from 94 different options, represented by strings, which correspond to 94 different classes. 我有一个JComboBox,用户可以从94个不同的选项中进行选择,这些选项由字符串表示,对应于94个不同的类。

All the 94 classes inherit from one parent class, called AbstractTiling. 所有94个类都继承自一个称为AbstractTiling的父类。 After Choosing one of those options (Strings from ComboBox) the chosen class should be instantiated. 选择这些选项之一(ComboBox中的字符串)后,应实例化所选的类。 But since there are 94 different possibilites I don't want to use 94 if statements. 但是由于有94种不同的可能性,所以我不想使用94 if语句。 So I tried it with a hashmap, but this leads to the problem that I still don't know the exact type I want to instantiate, so I can't use the methods that the classes overwrite from the parent class or have that the parent class doesn't. 因此,我使用了哈希图进行了尝试,但这导致了一个问题,即我仍然不知道要实例化的确切类型,因此我无法使用该类从父类覆盖的方法或让该父类覆盖的方法班没有。

In the code example there are just two entries in the hasmap as an example. 在代码示例中,作为示例,hasmap中只有两个条目。 Here is the code: 这是代码:

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.

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