lda*_*dam 6 java casting type-conversion
如果我使用这个类:
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];
}
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,我可以分配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
Run Code Online (Sandbox Code Playgroud)
据我所知,我在两种情况下都做同样的事情,但第一个例子编译得很好而第二个例子没有.
您正在使用不同的编译器选项.你一定是.这两段代码都是在Java 7规则下编译的; 既不编译Java 6规则.例如,拿你的第一段代码(你说的编译代码):
c:\Users\Jon\Test>javac -source 1.7 BooleanTest.java
(No console output, i.e. no errors)
c:\Users\Jon\Test>javac -source 1.6 BooleanTest.java
warning: [options] bootstrap class path not set in conjunction with -source 1.6
BooleanTest.java:10: error: inconvertible types
boolean bool = (boolean) objarray[1];
^
required: boolean
found: Object
1 error
1 warning
Run Code Online (Sandbox Code Playgroud)
编辑:我认为更改是在JLS(转换转换)的第5.5节中.
在Java 7的版本包括:
转换上下文允许使用以下之一:
- ...
- 缩小的引用转换(第5.1.6节),可选地后面是取消装箱转换(第5.1.8节)或未经检查的转换(第5.1.9节)
所述JLS第三版(爪哇5和6,基本上)包括:
转换上下文允许使用以下之一:
- ...
- 缩小的引用转换(第5.1.6节),可选地后跟未经检查的转换
请注意那里缺少"拆箱转换".
| 归档时间: |
|
| 查看次数: |
19765 次 |
| 最近记录: |