Java7 的 try-with-resources 非常棒,但我无法理解为什么需要在 try
语句中包含资源声明。我的直觉说以下应该是可能的:
CloseableResource thing;
try (thing = methodThatCreatesAThingAndDoesSomeSideEffect()) {
// do some interesting things
}
thing.collectSomeStats();
唉,这会导致语法错误(神秘地期待 ;
)。将类型定义/声明移动到 try
语句中是可行的,这当然会将 thing 移动到相应的范围内。当我想从我的 AutoClosable
中得到更多而不是关闭时,我可以弄清楚如何解决这个问题,我对为什么编译器这样要求它很感兴趣。
最佳答案
从 Java 9 开始,您可以在 block 外的 try-with-resources 中声明和初始化使用的变量。变量的唯一附加要求是它必须是 effectively final .
所以现在可以这样做:
CloseableResource thing = methodThatCreatesAThingAndDoesSomeSideEffect();
try (thing) {
// do some interesting things
}
thing.collectSomeStats();
希望对您有所帮助。
关于java - 为什么Java的try-with-resource中需要声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13836486/