我正在分析一个Android示例应用程序 - 蓝牙聊天:https://developer.android.com/samples/BluetoothChat/project.html。我在其内部类的构造函数ConnectThread中查看了BluetoothChatService类(https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html)。那里有这样的代码:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
(...)
public ConnectThread(BluetoothDevice device, boolean secure) {
(...)
BluetoothSocket tmp = null;
(...)
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
(...)
我不明白 - 为什么他们首先将对象分配给tmp值然后将其复制到mmSocket属性?他们可以这样做更简单一点:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
(...)
public ConnectThread(BluetoothDevice device, boolean secure) {
(...)
try {
if (secure) {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
mmSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
}
答案 0 :(得分:2)
很快,因为mmSocket
被标记为最终变量。
让我们看看您的代码版本。如果方法createRfcommSocketToServiceRecord
或方法createInsecureRfcommSocketToServiceRecord
抛出异常,则不初始化变量。因此,临时变量确保至少null
被分配给mmSocket
。
这就是原因。