java8的函数式接口

函数式接口

就是在java8里允许你为一个接口(只有一个实现的,声明为FunctionalInterface注解的)实现一个匿名的对象,大叔感觉它与.net平台的委托很类似,一个方法里允许你接收一个方法签名,这个方法在一个声明为FunctionalInterface的接口里,并且它是接口里唯一的方法。

java框架里也在用它

在我们的java框架里,很多地方在用函数式接口,下面的线程类的部分代码

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

事实上,在外部需要使用Runnable的实例时,可以直接构建一个匿名对象,像下面的代码是合法的

 super.periodicCheck(new PassableRunnable() {
      private boolean passed = false;

      @Override
      public boolean isPassed() {
        return passed;
      }

      @Override
      public void run() {
        System.out.println("test async task");
        passed = true;

      }
    });

下面是大叔在单元测试里写的一段实例代码,供大家学习和参考

 @Test
  public void testMethodFunction() {
    java8Fun(new Run() {
      @Override
      public void print() {
        System.out.println("类似.net里的委托!");
      }
    });
  }

  public void java8Fun(Run run) {
    System.out.println("执行java8函数式接口");
    run.print();
  }

  @FunctionalInterface
  interface Run {
    void print();
  }
posted @   张占岭  阅读(769)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-03-01 实时监控Cat之旅~分布式消息树的实现原理与测试
2012-03-01 你必须要知道的架构知识~第二章 代码是否面向对象,要看你的继承怎么用
点击右上角即可分享
微信分享提示