[英]ActionEvent.getSource: how to cast properly the source Object
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.我有下面的
ActionListener
,但我在if
语句中收到警告Unchecked cast: 'java.lang.Object' to 'javax.swing.JComboBox<java.lang.String>'
。 How can I solve it?我该如何解决? I want to invoke a method from the
JComboBox
API.我想从
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;
}
}
}
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.如果您打算使用
JComboBox
中使用通用<E>
任何方法,您可以在那里使用强制转换。 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>
.发出警告是因为编译器无法知道您的
JComboBox
是JComboBox<String>
还是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.转换是运行时的事情,Java 中的泛型只是占位符,以确保类型安全并使代码更具可读性。 Using Type Erasure, the compiler updates/modifies all statements involving generics with casting statements while generating the byte code (more info here ).
使用类型擦除,编译器在生成字节码时使用强制转换语句更新/修改所有涉及泛型的语句(更多信息请点击此处)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.