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
  • 166,747
  • 40
  • 210
  • 420
Jacopo Lanzoni
  • 1,125
  • 2
  • 10
  • 24
  • 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,499
  • 9
  • 25
  • 46
TroJaN
  • 123
  • 7