【问题标题】:How to use try-with-resources statement with interface object in Java如何在 Java 中对接口对象使用 try-with-resources 语句
【发布时间】: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? 但是,那里给出的解决方案需要我的场景使用嵌套的三元语句,这很快就会变得一团糟。

有人知道这个问题的优雅解决方案吗?

【问题讨论】:

    标签: java try-with-resources


    【解决方案1】:

    定义一个工厂方法来创建IFoo 实例:

    IFoo createInstance(int x) {
        if (x > 0) { return new Bar1(); }
        else if (x == 0) { return new Bar2(); }
        else { return new Bar3(); }
    }
    

    然后在你的 try-with-resources 初始化器中调用它:

    public void doLogic(int x) {
      try (IFoo ifoo = createInstance(x)) {
        // Logic with obj
      }
    }
    

    【讨论】:

    • 我将 createInstance(...) 作为静态方法添加到我的界面,效果很好。谢谢!
    【解决方案2】:

    我同意最好的解决方案是编写一个辅助方法,如this 答案。

    不过,我还想指出,嵌套的三元运算符不是混乱的。您根本不需要括号,并且通过良好的格式可以使其看起来像 switch 声明:

    try (IFoo foo = x > 20     ? new Bar1() :
                    x < 0      ? new Bar2() :
                    x == 10    ? new Bar3() :
                    x % 2 == 0 ? new Bar4() : 
                                 new Bar5()) {
            // do stuff
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-26
      • 2014-05-21
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多