尝试 - 最后使用密切的自动重构来尝试使用codestyle / checkstyle的资源

时间:2016-02-26 14:11:15

标签: java eclipse checkstyle try-with-resources try-finally

我现在在一家公司工作,直到大约一年前,使用了Java 1.6。他们切换到1.7,但仍有很多重构需要完成(我希望1.8很快就会提上议程)。

在Eclipse中,我们使用Checkstyle-plugin在项目中使用相同的代码。今天我们同意这样的结构:

Connection conn = null;
try{
    conn = new Connection();
    ...
} catch(Exception ex){
    ...
} finally{
    if (conn != null){
        conn.close();
    }
}
应该将

重写为从Java 1.7开始提供的try-with-resources

try(Connection conn = new Connection()){
    ...
} catch(Exception ex){
    ...
}

有没有一种方法可以使用Checkstyle-plugin,或者可能是Eclipse本身的原生代码,自动将旧版本重构为新版本?我个人有一个C#背景,并习惯using(Connection conn = new Connection()){ ... },所以我很高兴try-with-resources现在正在这里使用,我希望1.8很快就会加入(得到一些爱{ {1}}:D)。

如果有人知道Eclipse中的自动方式将LINQ构造更改为try-finally我会很感激(最好使用Checkstyle插件或本机Eclipse)。

1 个答案:

答案 0 :(得分:3)

很难快速改变它。请注意,有时try-catch中有另一个finally块,它会捕获关闭资源时抛出的异常。

try-with-resources语句允许您处理资源关闭异常(close方法抛出的异常将被抑制)。

我没有听说过这样的Eclipse功能,但是如果您只是出于这个目的而想要使用IntelliJ IDEA Community Edition IDE。

#1

您可以使用名为

的代码检查功能
  1. 'try finally' replaceable with 'try' with resources
  2. AutoCloseable used without 'try' with resources
  3. 您只需按 Ctrl + Alt + Shift ,编写检查名称并按 Enter 。之后,您将看到IDEA可以应用此模式的位置,但请注意,它不会涵盖100%的情况。

    #2

    另一种方法,更难,但可以大大定制Structural Search and Replace功能。您可以定义要更改的结构:

    try {
        $type$ $objectName$ = new $concreteType$($args$)
        $tryStatements$;
    } catch($exceptionType$ $exceptionName$) {
        $catchStatements$;
    } finally {
        $finallyStatements$;
    }
    

    最终结构:

    try ($type$ $objectName$ = new $concreteType$($args$)) {
      $tryStatements$;
    } catch($exceptionType$ $exceptionName$) {
        $catchStatements$;
    }
    

    在变量设置中,您可以要求$concreteType$实现AutoCloseable接口。

    但请注意:

    1. 我在这里摆脱finally阻止并支持单catch块。
    2. 还假设每个try-with-resources块会打开单个资源。
    3. 如前所述 - finally块中没有异常处理。
    4. 这个模板当然需要更多工作,而且可能不值得这样做。