簡體   English   中英

僅從JComboBox給出類名作為字符串的實例化類

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM