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

引入参数对象

此重构允许将方法的参数移动到新的包装类或某些现有的包装类。所有参数的用法都将替换为对包装类的相应调用。

执行重构

  1. 在代码编辑器中,将光标放置在要提取到包装类的参数上。
  2. 单击右键展示上下文菜单,选择重构 > 引入参数对象...
  3. 在打开的“引入参数对象”对话框中,提供重构选项。

    • “保留方法作为委托”:选择将原始方法保留为新创建方法的委托。
    • “参数类”: 在此区域中,选择是要创建新的包装参数类、在当前包装参数类中创建内部类,还是使用某些现有类。
    • “名称”:输入包装后参数的名称。
    • “要提取的参数”: 在此区域中,选中要提取到包装参数类的参数旁边的复选框。

      如下图所示:

      图1 引入参数对象

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

示例

例如,将helloworld参数提取到TextContainer类,以使生成的generateText方法调用将包含对TextContainer对象的调用。

重构前

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

class ExtractParameterObject {
    public static void main(String[] args) {
        System.out.println(generateText("Hello", "World!"));
    }

    private static String generateText(String hello, String world) {
        return hello.toUpperCase() + world.toUpperCase();
    }
}

重构后

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

class ExtractParameterObject {
    public static void main(String[] args) {
        System.out.println(generateText(new TextContainers("Hello", "World!")));
    }
    private static String generateText(TextContainers textContainers) {
        return textContainers.getHello().toUpperCase() + textContainers.getWorld().toUpperCase();
    }
}

同时,生成一个“com\refactoring\source\TextContainers.java”文件,文件内容如下:

package com.refactoring.source;
public class TextContainers {
    private final String hello;
    private final String world;
    public TextContainers(String hello, String world) {
        this.hello = hello;
        this.world = world;
    }
    public String getHello() {
        return hello;
    }
    public String getWorld() {
        return world;
    }
}

相关文档