1. 概述

重构(Refactoring)是指在不改变代码外部行为的前提下,优化其内部结构的一种技术手段。它帮助我们提升代码可读性、可维护性,以及更好地应用设计模式。

Eclipse 作为 Java 开发中广泛使用的 IDE,内置了丰富的重构功能,能帮助我们高效地完成代码优化工作。本文将重点介绍 Eclipse 中常见的重构操作,帮助你更轻松地提升代码质量。

建议:重构前务必确保有完善的测试用例,以防止引入 Bug。


2. 重命名(Renaming)

2.1 重命名变量和方法

重命名是最基础的重构操作之一,Eclipse 提供了快捷方式,操作步骤如下:

  • 选中要重命名的变量或方法
  • 右键点击,选择 Refactor > Rename
  • 输入新名称,按 Enter

或者使用快捷键:Alt+Shift+R

⚠️ 注意:Eclipse 会自动更新当前文件中所有引用该变量或方法的地方。

如果想更新其他类中的引用,可以在弹出窗口中点击 Options,选择更新范围:

Eclipse refactor 2

2.2 重命名包(Package)

重命名包也非常简单:

  • 在包资源管理器中选中包名
  • 右键选择 Refactor > Rename
  • 或者直接按 F2

弹出窗口中可设置是否更新子包及引用:

Eclipse refactor 4

2.3 重命名类和接口

类和接口的重命名方式与变量类似:

  • 右键点击类名或接口名,选择 Refactor > Rename
  • 或者在 Project Explorer 中按 F2

弹出窗口中可设置是否更新引用、生成注释等:

Eclipse refactor 5


3. 提取(Extracting)

提取是指将一段代码从当前位置移动到其他结构中,比如类、接口、方法等。这种重构有助于提升代码的结构清晰度和复用性。

3.1 提取类(Extract Class)

假设我们有如下 Car 类:

public class Car {

    private String licensePlate;
    private String driverName;
    private String driverLicense;

    public String getDetails() {
        return "Car [licensePlate=" + licensePlate + ", driverName=" + driverName
          + ", driverLicense=" + driverLicense + "]";
    }

    // getters and setters
}

我们想将驱动信息提取成一个独立类,操作步骤如下:

  • 右键点击类中任意位置
  • 选择 Refactor > Extract Class

设置新类名和要移动的字段:

Eclipse refactor 7

重构后代码如下:

public class Car {

    private String licensePlate;

    private Driver driver = new Driver();

    public String getDetails() {
        return "Car [licensePlate=" + licensePlate + ", driverName=" + driver.getDriverName()
          + ", driverLicense=" + driver.getDriverLicense() + "]";
    }

    //getters and setters
}

3.2 提取接口(Extract Interface)

假设我们有如下 EmployeeService 类:

public class EmployeeService {

    public void save(Employee emp) {
    }

    public void delete(Employee emp) {
    }

    public void sendEmail(List<Integer> ids, String message) {
    }
}

想提取接口:

  • 右键点击类名,选择 Refactor > Extract Interface
  • 或使用快捷键 Alt+Shift+T

设置接口名称和方法:

Eclipse refactor 8

重构后接口为:

public class EmployeeService implements IEmpService {

    @Override
    public void save(Employee emp) {
    }

    @Override
    public void delete(Employee emp) {
    }

    public void sendEmail(List<Integer> ids, String message) {
    }
}

3.3 提取父类(Extract Superclass)

如果我们想将 Employee 类中通用字段提取到父类:

public class Employee {

    private String name;

    private int age;

    private int experienceInMonths;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public int getExperienceInMonths() {
        return experienceInMonths;
    }
}

操作步骤如下:

  • 右键类名,选择 Refactor > Extract Superclass
  • 或使用快捷键 Alt+Shift+T

结果如下:

public class Employee extends Person {

    private int experienceInMonths;

    public int getExperienceInMonths() {
        return experienceInMonths;
    }
}

3.4 提取方法(Extract Method)

将一段代码块提取成独立方法,提升可读性。

原始代码:

public class Test {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

操作步骤如下:

  • 选中代码块
  • 右键选择 Refactor > Extract Method
  • 或使用快捷键 Alt+Shift+M

结果如下:

public class Test {

    public static void main(String[] args) {
        printArgs(args);
    }

    private static void printArgs(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

3.5 提取局部变量(Extract Local Variable)

将字面量提取为局部变量,提高可维护性。

原始代码:

System.out.println("Number of Arguments passed =" + args.length);

操作步骤如下:

  • 选中字符串
  • 右键选择 Refactor > Extract Local Variable
  • 或使用快捷键 Alt+Shift+L

结果如下:

final String prefix = "Number of Arguments passed =";
System.out.println(prefix + args.length);

3.6 提取常量(Extract Constant)

将字面值提取为类常量。

原始代码:

return 2 * 3.14 * radius;

操作步骤如下:

  • 选中数值
  • 右键选择 Refactor > Extract Constant

结果如下:

private static final double PI = 3.14;

public double circumference(double radius) {
    return 2 * PI * radius;
}

4. 内联(Inlining)

内联是重构的反向操作,即将方法或变量调用替换为原始表达式。

例如:

public class Util {

    public void isNumberPrime(int num) {
        boolean result = isPrime(num);
        if (result) {
            System.out.println("Number is Prime");
        } else {
            System.out.println("Number is Not Prime");
        }
    }

    // isPrime method
}

我们想移除 result 变量:

  • 选中变量
  • 右键选择 Refactor > Inline
  • 或使用快捷键 Alt+Shift+I

结果如下:

public class Util {

    public void isNumberPrime(int num) {
        if (isPrime(num)) {
            System.out.println("Number is Prime");
        } else {
            System.out.println("Number is Not Prime");
        }
    }

    // isPrime method
}

5. 向下推(Push Down)和向上提(Pull Up)

适用于类继承关系中,方法或字段在父子类之间的移动。

Push Down(向下推)

将父类中的方法或字段移动到子类中:

  • 右键类名,选择 Refactor > Push Down

Eclipse refactor 15

Pull Up(向上提)

将子类中的方法或字段移动到父类中:

  • 右键类名,选择 Refactor > Pull Up

Eclipse refactor 16


6. 修改方法签名(Change Method Signature)

修改方法参数、返回值或异常声明等。

操作步骤如下:

  • 将光标置于方法中
  • 右键选择 Refactor > Change Method Signature
  • 或使用快捷键 Alt+Shift+C

弹出窗口中可修改方法签名:

Eclipse refactor 17


7. 移动(Moving)

将方法移动到更合适的类中,提升面向对象设计。

例如将 Customer 类中的 movieCost() 方法移动到 Movie 类中:

  • 选中方法
  • 右键选择 Refactor > Move
  • 或使用快捷键 Alt+Shift+V

Eclipse refactor 18

重构后 Customer 类变为:

public class Customer {

    private String name;
    private String address;
    private List<Movie> movies;

    public double totalCost() {
        double result = 0;
        for (Movie movie : movies) {
            result += movie.movieCost();
        }
        return result;
    }

    // other methods
}

8. 总结

Eclipse 提供了强大且高效的重构工具,涵盖了从基础重命名、提取类/接口/方法,到内联、移动、签名修改等多种高级操作。

熟练掌握这些重构技巧,不仅能提升代码质量,还能显著提高开发效率。

建议:多使用快捷键,少用鼠标操作,重构效率翻倍。

🔗 参考文档Eclipse 官方重构文档


原始标题:Refactoring in Eclipse | Baeldung