浅谈JAVA函数式接口

2022/4/22 20:13:24

本文主要是介绍浅谈JAVA函数式接口,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

什么是函数式接口

定义: 有且仅有一个抽象方法的接口

java中有那些函数式接口

四大内置的函数式接口
Consumer,Supply,Funcation,Predicate
其后面会衍生出其他的函数式接口
具体可参考JDK中的java.util.function包

如何自定义函数式接口

1.继承一个函数式接口
2.将接口上加上@FuncationInterface

示例:

/**
 * 报表编排
 *
 * @author Yangqi.Pang
 */
@FunctionalInterface
public interface ReportPipeline extends Consumer<ReportPipeline.ReportContext> {

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    class ReportContext {
        /**
         * 报表模板
         */
        private ReportTemplate reportTemplate;

        /**
         * 报表请求参数
         */
        private JSONObject reportReq;

        /**
         * 模板Id
         */
        private Long templateId;

        /**
         * 查询参数Map
         */
        private Map<String, Object> fieldMap;

        /**
         * 返回结果
         */
        private List<JSONObject> pageResults;

        /**
         * 查询类型
         */
        private QueryType queryType;

        /**
         * 参数校验
         */
        public void validate() {
            ExceptionUtil.validate(Objects.nonNull(templateId), "模板Id不能为空");
            ExceptionUtil.validate(Objects.nonNull(reportReq), "传参不能为空");
            ExceptionUtil.validate(Objects.nonNull(queryType), "查询类型不能为空");
        }

        @Getter
        @AllArgsConstructor
        public enum QueryType {
            /**
             * 分页查询
             */
            PAGE,
            /**
             * Excel导出
             */
            EXCEL_EXPORT
        }
    }
}

对函数式接口的理解

1.如果我们定义这个类只能做一件事情的时候,我们就可以使用函数式接口,这个就是用来限定这个类的
2.与接口的不同之处就是,接口可以用来做多个事情,没有限制
3.函数式接口独特之处,是要把行为也抽象为一个对象

示例:我们就只定义这个类只能做这一件事情

/**
 * 分页查询
 *
 * @author Yangqi.Pang
 */
@Slf4j
@Component
public class PageQueryPipeline implements ReportPipeline {

    @Resource
    private ReportMapper reportMapper;

    @Override
    public void accept(ReportPipeline.ReportContext reportContext) {
        ReportTemplate reportTemplate = reportContext.getReportTemplate();
        List<JSONObject> results = reportMapper.query(reportTemplate.getSql(), reportContext.getFieldMap());
        reportContext.setPageResults(results);
    }
}


这篇关于浅谈JAVA函数式接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程