更新时间:2025-08-19 GMT+08:00
分享

反转布尔值

通过此重构,可以反转布尔变量的值或方法的返回值。

执行重构

  1. 在代码编辑器中,将光标放置在布尔变量或具有布尔返回值的方法的声明上。
  2. 单击右键展示上下文菜单,选择重构 > 反转布尔值
  3. 在打开的“反转布尔值”对话框中,为反转变量或方法提供新名称。如下图所示:

    图1 反转布尔值

  4. 单击“重构”以应用重构。

示例

例如,反转condition变量和checkCondition方法的值。

重构前

“com\refactoring\source\Invert.java”文件内容如下:

class Invert {
    private static double a;
    public static void main(String[] args) {
        boolean condition = true;
        if (condition) {
            System.out.println("Hello World!");
        }
    }
    public static boolean checkCondition() {
        if (a > 15 && a < 100) {
            a = 5;
            return true;
        }
        return false;
   }
}

重构后

“com\refactoring\source\Invert.java”文件内容如下:

class Invert {
    private static double a;
    public static void main(String[] args) {
        boolean condition = false;
        if (!condition) {
            System.out.println("Hello World!");
        }
    }
    public static boolean checkCondition() {
        if (a > 15 && a < 100) {
            a = 5;
            return false;
        }
        return true;
   }
}

相关文档