构造函数当做Function用做方法入参

1.先有一个类,有一个构造函数

public abstract class AbstractMonitorAction<T> implements Action<T>{
}

public class StopMonitorAction extends AbstractMonitorAction<CheckResult> {
        private final List<ScanResult> scanResults;
        private List<CheckResult> checkResults;

        public StopMonitorAction(List<ScanResult> scanResults) {
            this.scanResults = scanResults;
        }

        @Override
        public void execute() {
            checkResults = Lists.newArrayList();
            List<List<ScanResult>> partitions = Lists.partition(scanResults, 500);

            for (List<ScanResult> partition : partitions) {
                processPartition(partition);
            }
        }
}

2.定义一个Function用来指定不同的构造函数

Function<List<ScanResult>,Action<CheckResult>>

入参:List
出参:Action 接口

3.分析上述构造函数

  1. 发现构造函数的入参就是List
  2. 构造函数一般返回类自己对象,因为类有继承关系,父类有实现接口逻辑,用多态特性可以用接口接受返回类型
  3. 所有构造函数是可以用做Function类型的接收的

4.实际定义例子

private void processScanResults(List<ScanResult> scanResults, String actionName, List<CheckResult> checkResults, Function<List<ScanResult>, Action<CheckResult>> actionConstructor) {
        List<ScanResult> filteredResults = scanResults.stream()
                .filter(scanResult -> scanResult.getScanValue().equalsIgnoreCase(actionName))
                .collect(Collectors.toList());

        if (!filteredResults.isEmpty()) {
            Action<CheckResult> action = actionConstructor.apply(filteredResults);
            action.execute();
            checkResults.addAll(action.getResult());
        }
    }
# 使用,其中StopMonitorAction::new 会自动识别为是Function<List<ScanResult>, Action<CheckResult>> 类型
processScanResults(scanResults, TaiShanMonitorScanExector.MonitorAction.STOP_MONITOR.name(), checkResults, StopMonitorAction::new);

5.方法引用的参数

  1. 无参数构造函数
    如果目标类型是一个没有参数的构造函数,可以使用 Supplier 接口:
Supplier<StopMonitorAction> supplier = StopMonitorAction::new;
StopMonitorAction action = supplier.get();
  1. 带一个参数的构造函数
    如果目标类型是一个带一个参数的构造函数,可以使用 Function 接口:
Function<String, StopMonitorAction> function = StopMonitorAction::new;
StopMonitorAction action = function.apply("exampleName");
  1. 带两个参数的构造函数
    如果目标类型是一个带两个参数的构造函数,可以使用 BiFunction 接口:
BiFunction<String, Integer, StopMonitorAction> biFunction = StopMonitorAction::new;
StopMonitorAction action = biFunction.apply("exampleName", 123);
posted @   SpecialSpeculator  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2023-08-23 创建map同时赋值
点击右上角即可分享
微信分享提示