JDK1.7增加了try-with-source語法。在try中聲明一個或者多個資源,在try塊代碼執行完成后自動關閉流,不用再寫close()進行手動關閉。
1 try(Resource res = xxx)//可指定多個資源 2 { 3 work with res 4 } 5 // 實現了AutoCloseable接口的類的對象就是資源
於是我想在代碼中改成try-with-resource的寫法,但是修改后IDEA一直會報編譯時錯誤:
Cannot assign a value to final variable 'connection'
無法給final類型的變量'connection'賦值
后面的statement, resultSet有同樣的錯誤。
於是我去找了一下官方文檔,官方文檔的try-with-resource中有這樣一段描述:
https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.20.3
It is a compile-time error if
final
appears more than once as a modifier for each variable declared in a resource specification.A variable declared in a resource specification is implicitly declared
final
if it is not explicitly declaredfinal
(§4.12.4).如果final作為資源中聲明當前變量的修飾符出現多次,則會出現編譯時錯誤。
在資源中聲明的變量如果沒有顯式聲明為final,則將被隱式聲明為final。
顯然,try-with-resource中聲明的變量會被隱式地加上final關鍵字,所以無法再進行賦值。
因此,對於這種情況我們無法使用try-with-resource.