在 Try with Resource 语句中使用的任何变量都需要在 Try 语句中声明,直至 Java 8 版本。从Java 9开始,此限制已被删除,并且任何final 或有效final变量已在尝试阻止。 Effectively Final 表示变量一旦初始化就无法更改。
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class EffectivelyFinalTest { private static File file = new File("try_resources.txt"); public static void main(String args[]) throws IOException { file.createNewFile(); BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); <strong>try</strong>(<strong>bufferedReader</strong>) { System.out.println("Can Use Final or Effectively Final in Try with Resources!"); } finally { System.out.println("In finally block"); } } }
<strong>Can Use Final or Effectively Final in Try with Resources! In finally block</strong>
以上是Java 9中的try-with-resources中的有效final变量?的详细内容。更多信息请关注PHP中文网其他相关文章!