ActionEvent.getSource: how to cast properly the source Object

Jacopo Lanzoni :

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

}
TroJaN :

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).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379183&siteId=1