【发布时间】:2013-03-24 01:17:59
【问题描述】:
如果我使用这个类:
public class BooleanTest {
public static void main(String args[]) {
final Object[] objarray = new Object[2];
try {
objarray[0] = "Hello World!";
objarray[1] = false;
} catch (NullPointerException e) {
}
boolean bool = (boolean) objarray[1];
}
}
它工作正常,我可以分配boolean 没问题。为什么我在询问用户密码时不能做同样的事情?
final Object result[] = new Object[2];
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,0));
JLabel label = new JLabel();
label.setHorizontalAlignment(SwingConstants.LEADING);
JTextField input = new JTextField();
input.setHorizontalAlignment(SwingConstants.CENTER);
JCheckBox checkbox = new JCheckBox("Pair with this device");
checkbox.setHorizontalAlignment(SwingConstants.LEADING);
panel.add(label);
panel.add(input);
panel.add(checkbox);
if (wrong) {
label.setText("Wrong password. Please enter the password from the other device:");
} else {
label.setText("Please enter the password from the other device:");
}
int response = JOptionPane.showConfirmDialog(SendGUI.this, panel, "Enter password", JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.OK_OPTION) {
result[0] = input.getText();
result[1] = (boolean)checkbox.isSelected();
} else {
result[0] = null;
result[1] = false;
}
}
});
} catch (InterruptedException e) {
} catch (InvocationTargetException e) {
}
boolean pair = (boolean)result[1]; //inconvertible type, expected boolean found Object
据我所知,我在这两种情况下都在做同样的事情,但是第一个示例编译得很好,而第二个示例则没有。
【问题讨论】:
-
你能把你在最后一个代码中得到的错误贴出来吗?
-
@MiguelPrz 在我的代码中,
inconvertible type, expected boolean found Object -
@LoganDam:这是编译时错误吗?在这两种情况下,您是否使用相同的编译器(具有相同的选项)?
-
@JonSkeet 是的。我使用 Netbeans 7.3 作为我的 IDE 并用它编译这两种情况。在第二个示例中,当它警告我编译器错误时,我仍然单击运行,当它最终到达该代码块时,我得到
Exception in thread "Thread-3" java.lang.RuntimeException: Uncompilable source code - inconvertible types required: boolean found: java.lang.Object -
@LoganDam:首先不尝试运行带有编译时错误的代码!你确定你的第一个代码编译没有错误吗?
标签: java casting type-conversion