更新时间:2024-04-12 GMT+08:00
分享

提取方法

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

执行重构

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

  4. 单击Refactor以应用重构。

示例

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

重构前

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

重构后

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);
      }
   }
}
分享:

    相关文档

    相关产品