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

引入功能参数

此重构允许您基于适当的函数接口使用匿名类(或函数表达式)包装代码片段,并将其用作方法的参数。

执行重构

  1. 在代码编辑器中,选择要转换为函数参数的表达式。
  2. 在主菜单或编辑器上下文菜单中,选择Refactor>Introduce Functional Parameter
  3. 在打开的Introduce Functional Parameter对话框中,提供引入参数的名称和其他重构选项。

    • Parameters of type列表中,为提取的参数选择其中一种的类型。
    • 选择是否应将提取的参数声明为final参数。
    • 要保留原始方法并使用引入的参数定义新方法,请选中Delegate via overloading method选项。
    • 要让CodeArts IDE生成函数表达式而不是匿名类,请选中Convert to functional expression复选框。

  4. 单击Refactor以应用重构。

示例

例如,让我们提取表达式“Hello World!”.toUpperCase()作为generateText方法的参数。通过使用Convert to functional expression选项,我们可以通过两种方式完成:函数表达式或匿名类。

重构前

class IntroduceFunctionalParameter {
    public static void main(String[] args) {
        System.out.println(generateText());
    }

    private static String generateText() {
        return "Hello World!".toUpperCase();
    }
}

重构后(函数表达式)

import java.util.function.Supplier;

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

    private static String generateText(Supplier<String> supplier) {
        return supplier.get().toUpperCase();
    }
}

重构后(匿名类)

import java.util.function.Supplier;

class IntroduceFunctionalParameter {
    public static void main(String[] args) {
        System.out.println(generateText(new Supplier<String>() {
            public String get() {
                return "Hello World!".toUpperCase();
            }
        }));
    }

    private static String generateText(Supplier<String> supplier) {
        return supplier.get();
    }
}
分享:

    相关文档

    相关产品