问题
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