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

提取方法

此重构允许将任意代码片段移动到单独的方法中,并将其替换为对此新创建的方法的调用。这与内联方法相反。

执行重构

  1. 在代码编辑器中,选择要提取到新方法的代码片段。
  2. 单击右键展示上下文菜单,选择重构 > 提取方法...,或按“Ctrl+Shift+Alt+M”
  3. 在打开的“提取方法”对话框中,提供新方法的名称和可见性修饰符,并从选择范围中选择变量作为方法参数。

    如下图所示:

    图1 提取方法

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

示例

例如,将包含println语句的for循环提取到一个新的printText方法中,其中text和n作为方法的参数。

重构前

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

class ExtractMethod {
   public static void main(String[] args) {
      String text = "Hello World!";
      int n = 5;

      for (int i = 0; i < n; i++) {
         System.out.println(text);
      }
   }
}

重构后

将for循环提取到新的方法“printText”后,“com\refactoring\source\ExtractMethod.java”文件内容如下:

class ExtractMethod {
   public static void main(String[] args) {
      String text = "Hello World!";
      int n = 5;

      printText(text, n);
   }

   public static void printText(String text, int n) {
      for (int i = 0; i < n; i++) {
         System.out.println(text);
      }
   }
}

相关文档