【发布时间】:2022-01-19 15:35:42
【问题描述】:
我想使用 try-with-resource 来切换上下文,但似乎 try() 不能在不声明变量的情况下使用资源,这会使代码不那么优雅。例如
class SwitchContext implements Closeable {
public SwitchContext(String newContext) {
//Set new context to local thread
}
public void close() {
//Restore old context to local thread
}
及用法:
String func() {
try (new SwitchContext(newContext)) {
//Do something
return "dummy";
}
void func2() {
try (new SwitchContext(newContext)) {
//Do something
}
但我在 try() 上遇到语法错误。只有当我这样写:
try (SwitchContext c = new SwitchContext(newContext)) {
它通过了编译。
最优雅的方法是什么?
更新
由于在某些答案中人们不明白我要做什么,我会尝试更好地解释。我正在尝试以更优雅的方式执行以下逻辑:
void func() {
Context old = ContextUtil.getCurrentContext();
try() {
ContextUtil.setContext(A)
//Do something or call other methods
//Any method than need the context use ContextUtil.getCurrentContext()
} finally () {
ContextUtil.setContext(old)
}
}
【问题讨论】:
-
这样做有什么意义?如果你不将它分配给一个变量,你就不能在 try 块中使用它,因此你可能根本不声明它。
-
@OHGODSPIDERS 如果它在其构造函数和 close() 方法中有一些设置和清理,这是 try 块内的代码所必需的。
-
将其分配给变量似乎是最简单的解决方案。或者也许使用传统的 try/finally 块而不是可关闭的对象会更合适。
-
@khelwood 好吧,我没想到。仍然看起来像一个奇怪的边缘情况,而不是真正的可关闭资源通常用于什么。
-
想知道:您对得到的答案还有疑问吗?如果没有,并且您的问题已解决,请考虑在某个时候接受其中一个答案。