简体   繁体   English

如何在Java中将try-with-resources语句与接口对象一起使用

[英]How to use try-with-resources statement with interface object in Java

I would like to use a try-with-resources statement to define an interface object as a concrete class. 我想使用try-with-resources语句将接口对象定义为具体类。 Here is some sample code loosely defining my interface and classes. 这是一些示例代码,它们松散地定义了我的接口和类。

interface IFoo extends AutoCloseable
{
    ...
}

class Bar1 implements IFoo
{
    ...
}

class Bar2 implements IFoo
{
    ...
}

class Bar3 implements IFoo
{
    ...
}

// More Bar classes.........

I now need to define an IFoo object, but the concrete class is conditional on another variable of my code. 现在,我需要定义一个IFoo对象,但是具体的类取决于我的代码的另一个变量。 The logic is the same for all concrete classes. 所有具体类的逻辑都是相同的。 So I would like to use a try-with-resources statement to define the interface object, but I need to use a conditional statement to see which concrete class I need define the interface object as. 因此,我想使用try-with-resources语句定义接口对象,但是我需要使用条件语句来查看需要将接口对象定义为哪个具体类。

Logically, this is what I am looking to do: 从逻辑上讲,这就是我要做的事情:

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
    }
}

The only resource I have found relating to this is @Denis's question here: How to use Try-with-resources with if statement? 我发现与此有关的唯一资源是@Denis的问题: 如何在if语句中使用Try-with-resources? However, the solution given there would require nested ternary statements for my scenario, and that gets messy real fast. 但是,那里给出的解决方案将需要针对我的场景的嵌套三元语句,并且很快就会变得混乱。

Does anyone know of an elegant solution for this issue? 有人知道这个问题的解决方案吗?

Define a factory method to create the IFoo instance: 定义一个工厂方法来创建IFoo实例:

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

then invoke that in your try-with-resources initializer: 然后在您的try-with-resources初始化程序中调用它:

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

I agree that the best solution is to write a helper method like in this answer. 我同意最好的解决方案是编写一个类似于答案的辅助方法。

However, I also want to point out that nested ternary operators are not messy. 但是,我也想指出,嵌套三元运算符并不杂乱。 You do not need brackets at all, and with good formatting it can be made to look like a switch statement: 您完全不需要方括号,并且格式良好,可以使它看起来像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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM