迁岂罚 发表于 2025-6-9 08:54:32

什么是函数回调

什么是函数回调?

介绍

函数回调是一种编程概念,它描述的是这样一个过程:一个函数(称为回调函数)作为参数传递给另一个函数(称为调用函数),当满足一定条件或者在某个特定时刻,调用函数会调用传递过来的回调函数。这种机制允许程序员在编写代码时,能够在不同的上下文中重用函数,同时也能实现异步处理、事件驱动编程以及模块间的松散耦合
示例

以Java为例,由于Java语言不直接支持函数指针,因此通常通过接口实现回调机制,比如函数式接口Function
// 这是一个回调接口public interface Function {    /**   *      * Applies this function to the given argument.   *   * @param t the function argument   * @return the function result   */    R apply(T t);    }public class TestFunctionCallBack {    @Test    public void mainMethod(){      String str1 = test(String::toUpperCase,"hello");      String str2 = test(this::switchCase,"HeLLo");      log.info("str1:{}", str1);      log.info("str2:{}", str2);    }    /**   * 这个方法(调用函数)接收 函数作为参数   * @param function   * @param args   * @return   */    public static String test(Function function,String args){      //调用回调函数的具体方法      return "{"+function.apply(args)+"}";    }    /**   * 大写转小写,小写转大写   *   * @param source 来源   * @return {@link String}   */    public String switchCase(String source){      char[] charArray = source.toCharArray();      for (int i = 0; i < charArray.length; i++) {            char c = charArray;            if (c >= 'a' && c = 'A' && c
页: [1]
查看完整版本: 什么是函数回调