【发布时间】:2016-03-27 14:18:40
【问题描述】:
我想使用try-with-resources 语句将接口对象定义为具体类。这是一些松散定义我的接口和类的示例代码。
interface IFoo extends AutoCloseable
{
...
}
class Bar1 implements IFoo
{
...
}
class Bar2 implements IFoo
{
...
}
class Bar3 implements IFoo
{
...
}
// More Bar classes.........
我现在需要定义一个IFoo 对象,但具体类取决于我的代码的另一个变量。所有具体类的逻辑都是相同的。所以我想用try-with-resources语句来定义接口对象,但是我需要使用条件语句来查看我需要将接口对象定义为哪个具体类。
从逻辑上讲,这就是我想要做的:
public void doLogic(int x)
try (
IFoo obj;
if (x > 0) { obj = new Bar1(); }
else if (x == 0) { obj = new Bar2(); }
else { obj = new Bar3(); }
)
{
// Logic with obj
}
}
我发现与此相关的唯一资源是@Denis 的问题: How to use Try-with-resources with if statement? 但是,那里给出的解决方案需要我的场景使用嵌套的三元语句,这很快就会变得一团糟。
有人知道这个问题的优雅解决方案吗?
【问题讨论】: