从源码角度学习java函数式编程

以你之姓@ 2022-11-22 05:13 141阅读 0赞

Java 函数式编程

简单来说,函数式编程就是被注解@FunctionalInterface修饰的接口。

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.TYPE)
  4. public @interface FunctionalInterface {}
  5. // 以jdk中的LongToIntFunction,相当于就是一个接口
  6. @FunctionalInterface
  7. public interface LongToIntFunction {
  8. /**
  9. * Applies this function to the given argument.
  10. *
  11. * @param value the function argument
  12. * @return the function result
  13. */
  14. int applyAsInt(long value);
  15. }
  16. // 这个接口可以被直接传入到函数中直接使用
  17. // 以jdk中的LongPipeline为例
  18. @Override
  19. public final IntStream mapToInt(LongToIntFunction mapper) {
  20. Objects.requireNonNull(mapper);
  21. return new IntPipeline.StatelessOp<Long>(this, StreamShape.LONG_VALUE,
  22. StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
  23. @Override
  24. Sink<Long> opWrapSink(int flags, Sink<Integer> sink) {
  25. return new Sink.ChainedLong<Integer>(sink) {
  26. @Override
  27. public void accept(long t) {
  28. downstream.accept(mapper.applyAsInt(t));
  29. }
  30. };
  31. }
  32. };
  33. }

那么,函数是编程的interface怎么实现呢?由之前讲注解的时候我们提到了,jdk内置的元注解,编译器是会识别并给被该注解修饰的对象赋予编译器预先定义好的行为的。

但是,接口始终是接口,不拥有实际的行为,实际的行为还是需要具体的实现类来定义,那么我们来看看,函数式接口应该如何implement。以Springboot中的函数式接口TargetServerConnection为例

  1. @FunctionalInterface
  2. public interface TargetServerConnection {
  3. /**
  4. * Open a connection to the target server with the specified timeout.
  5. * @param timeout the read timeout
  6. * @return a {@link ByteChannel} providing read/write access to the server
  7. * @throws IOException in case of I/O errors
  8. */
  9. ByteChannel open(int timeout) throws IOException;
  10. }
  11. // 实现类 SocketTargetServerConnection.java 中的open方法
  12. @Override
  13. public ByteChannel open(int socketTimeout) throws IOException {
  14. SocketAddress address = new InetSocketAddress(this.portProvider.getPort());
  15. logger.trace(LogMessage.format("Opening tunnel connection to target server on %s", address));
  16. SocketChannel channel = SocketChannel.open(address);
  17. channel.socket().setSoTimeout(socketTimeout);
  18. return new TimeoutAwareChannel(channel);
  19. }
  20. // 在 HttpTunelServer中使用
  21. protected ServerThread getServerThread() throws IOException {
  22. synchronized (this) {
  23. if (this.serverThread == null) {
  24. ByteChannel channel = this.serverConnection.open(this.longPollTimeout);
  25. this.serverThread = new ServerThread(channel);
  26. this.serverThread.start();
  27. }
  28. return this.serverThread;
  29. }
  30. }

可以看到,这种写法就是传统的接口实现方法,所以我们讲,函数式接口就是一个接口,不是什么高级语法糖,@FunctionalInterface注解也并不会提供额外的功能,只是通过该注解修饰的接口,让编译器知道,然后去判定该接口是否定义得合乎函数式接口的定义规则。

那么,到底函数式接口该如何使用呢?

要回答这个问题可不简单,先来看看下面的代码

  1. @FunctionalInterface
  2. public interface ExitCodeExceptionMapper {
  3. int getExitCode(Throwable exception);
  4. }

这个是springboot框架中定义获取退出码的函数式接口

  1. // SpringApplicationTest.java
  2. @Bean
  3. ExitCodeExceptionMapper exceptionMapper() {
  4. return (exception) -> {
  5. if (exception instanceof IllegalStateException) {
  6. return 11;
  7. }
  8. return 0;
  9. };
  10. }
  11. // SpringApplication.java
  12. private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) {
  13. if (context == null || !context.isActive()) {
  14. return 0;
  15. }
  16. ExitCodeGenerators generators = new ExitCodeGenerators();
  17. Collection<ExitCodeExceptionMapper> beans = context.getBeansOfType(ExitCodeExceptionMapper.class).values();
  18. generators.addAll(exception, beans);
  19. return generators.getExitCode();
  20. }

该函数式接口被使用的地方,从第一个例子我们可以知道,函数式接口所诠释的类型等价于其唯一方法的返回值所代表的类型。第二个例子告诉我们,函数式接口不一定非要被实现才能获得实际行为,也可以通过反射得到。

源码分析结束了,我们来实现一个例子

  1. // 定义一个函数式接口 Demo1.java
  2. @FunctionalInterface
  3. public interface Demo1 {
  4. String getName(Integer code);
  5. }
  6. // 实现类 Demo2.java
  7. public class Demo2 implements Demo1{
  8. @Override
  9. public String getName(Integer code) {
  10. StringBuilder builder = new StringBuilder();
  11. return builder.append("my name is ").append(code).append("!").toString();
  12. }
  13. }
  14. // 调用方 Demo3.java
  15. public class Demo3{
  16. public static void main(String[] args){
  17. // 在使用过程中实例化
  18. Demo1 demo1 = new Demo1() {
  19. @Override
  20. public String getName(Integer code) {
  21. return new StringBuilder().append("my name is ").append(code).append("!").toString();
  22. }
  23. };
  24. System.out.println(demo1.getName(1));
  25. System.out.println(demo1.getName(2));
  26. // 普通接口
  27. Demo1 demo2 = new Demo2();
  28. System.out.println(demo2.getName(1));
  29. System.out.println(demo2.getName(2));
  30. // 简单的函数式编程
  31. Demo1 demo3 = code -> {
  32. return new StringBuilder().append("my name is ").append(code).append("!").toString();
  33. };
  34. System.out.println(demo3.getName(1));
  35. System.out.println(demo3.getName(2));
  36. }
  37. }

上面三个打印结果是一样的,也就是说,对于函数式接口,我们可以直接用这样的语法

  1. Demo1 demo3 = code -> {
  2. return new StringBuilder().append("my name is ").append(code).append("!").toString();
  3. };

来定义出其函数体。

带来的好处

简洁和稳定

炒鸡辣鸡原创文章,转载请注明来源

发表评论

表情:
评论列表 (有 0 条评论,141人围观)

还没有评论,来说两句吧...

相关阅读