How to cast type safety a Object to JComboBox<String>?

二次信任 提交于 2020-01-25 10:12:27

问题


I have this code:

@Override
public void itemStateChanged(ItemEvent evt) {
    if (evt.getStateChange() == ItemEvent.SELECTED) {
        Object sourceObject = evt.getSource();

        if (sourceObject instanceof JComboBox<?>) {
            JComboBox<String> jComboBox = (JComboBox<String>) sourceObject;
        }
    }
}

What is the best and correct casting for generics type safety and avoiding suppress the warning?


回答1:


You nailed it. Runtime instanceof checks don't check generic parameters so the way you have shown it is the standard way that it is done.



来源:https://stackoverflow.com/questions/59539568/how-to-cast-type-safety-a-object-to-jcomboboxstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!