Java中空赋值的优点是什么?

Dim*_*ima 1 java

我看到很多像这样的代码:

SomeObject someObject = null;

try{

   someObject = ObjectFactory.createSomeObject();
   ...
Run Code Online (Sandbox Code Playgroud)

与此相比,这样做有什么好处:

SomeObject someObject = ObjectFactory.createSomeObject();
Run Code Online (Sandbox Code Playgroud)

Chr*_*wes 8

这是一个常用的习惯用法,你必须用null初始化连接,因为Java只支持类成员的初始化,在这个范围内你必须用它初始化它null,因为ConnectionFactory.create()也许会引发异常.

您可以使用它来扩展变量的范围并在以后使用它,例如关闭连接句柄.

Connection connection = null;

try {
   connection = ConnectionFactory.create();

   [...]

   // More code which probably causes an exception

} catch(Exception e) {
   // Handle the exception
} finally {
    if(connection != null) {
      // Cleanup and close resources later
      connection.close()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果初始化catch块中的连接,则finally块或以下代码不可见.