3

I fear I may be making a newbie error here. I have the ActionListener below, but I get the warning Unchecked cast: 'java.lang.Object' to 'javax.swing.JComboBox<java.lang.String>' inside the if statement. How can I solve it? I want to invoke a method from the JComboBox API.


I am not interested in suppressing the warning.

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;
        }
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jacopo Lanzoni
  • 1,264
  • 2
  • 11
  • 25
  • 2
    You can't. See this for more details: [How do I address unchecked cast warnings?](https://stackoverflow.com/questions/509076/how-do-i-address-unchecked-cast-warnings) – dems98 Mar 27 '20 at 15:20

1 Answers1

3

To remove the warning without suppressing, you will have to compromise with the generics and change the code to:

JComboBox<?> comboBox;
if (source instanceof JComboBox) {
    comboBox = (JComboBox<?>) source;
}

And if you are going to use any method from JComboBox which uses the generic <E>, you can use casting there. For example:

String s = (String) comboBox.getItemAt(0);

Explanation:

The warning was given because there is no way for the compiler to know whether your JComboBox is a JComboBox<String> or a JComboBox<Integer>.

Casting is a runtime thing and generics in Java are just placeholders to ensure type safety and to make the code more readable. Using Type Erasure, the compiler updates/modifies all statements involving generics with casting statements while generating the byte code (more info here).

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
TroJaN
  • 123
  • 7
  • Thank you, this is exactly what I was looking for. And thanks for the clear explanation! – Jacopo Lanzoni Mar 27 '20 at 15:39
  • 1
    thanks @Trojan by the way using jdk 16 or above we can use pattern match the if statment could be written as `if (source instanceof JComboBox> comboBox)` this will create JcomboBOx> called comboBox if the source is instance of it so no need to create the variable or do the cast –  Feb 12 '23 at 15:15