实例化类只将类名称作为JComboBox中的字符串

时间:2021-02-27 12:44:38

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. After Choosing one of those options (Strings from ComboBox) the chosen class should be instantiated. But since there are 94 different possibilites I don't want to use 94 if statements. 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.

所有94个类都从一个父类继承,称为AbstractTiling。选择其中一个选项(ComboBox中的字符串)之后,应该实例化所选的类。但由于有94种不同的可能性,我不想使用94 if语句。所以我用一个hashmap尝试了它,但是这导致了我仍然不知道我想要实例化的确切类型的问题,所以我不能使用类从父类重写的方法或者那个父类上课没有。

In the code example there are just two entries in the hasmap as an example. Here is the code:

在代码示例中,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);          
    }
});

1 个解决方案

#1


0  

I think you can do it using the Class class. These links have more info.

我认为你可以使用Class类来完成它。这些链接有更多信息。

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

“Class.forName()”和“Class.forName()。newInstance()”有什么区别?

How do I get a class reference from a String in Java?

如何从Java中的String获取类引用?

Good luck!

祝你好运!

#1


0  

I think you can do it using the Class class. These links have more info.

我认为你可以使用Class类来完成它。这些链接有更多信息。

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

“Class.forName()”和“Class.forName()。newInstance()”有什么区别?

How do I get a class reference from a String in Java?

如何从Java中的String获取类引用?

Good luck!

祝你好运!