Action Event.getSource: how to cast properly the source Object
I’m afraid I might make a newbie mistake here. I have ActionListener
below, but I get the warning Unchecked cast: 'java.lang.Object' to 'javax.swing.JComboBox<java.lang.String>'
stated in if
. How do I fix it? I want to call a method API from JComboBox
.
I’m not interested in suppressing warnings.
public class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent actionEvent) {
Object source = actionEvent.getSource();
JComboBox<String> comboBox;
if (source instanceof JComboBox) {
comboBox = (JComboBox<String>) source;
}
}
}
Solution
To remove the warning without suppression, you will have to compromise with generics and change the code to:
JComboBox<?> comboBox;
if (source instanceof JComboBox) {
comboBox = (JComboBox<?>) source;
}
If you want to use any method in JComboBox
and it uses generic <E>
, you can use type conversion there. For example:
String s = (String) comboBox.getItemAt(0);
Explanation:
The warning is issued because the compiler cannot know if your JComboBox
exists. is JComboBox<String> or JComboBox<Integer>
Conversion is a runtime thing, and generics in Java are just placeholders to ensure type safety and make the code more readable. With type removal, the compiler updates/modifies all statements involving generics and cast statements when generating bytecode (more information here).