java8的函数式接口

栏目: Java · 发布时间: 7年前

内容简介:就是在java8里允许你为一个接口(只有一个实现的,声明为FunctionalInterface注解的)实现一个匿名的对象,大叔感觉它与.net平台的委托很类似,一个方法里允许你接收一个方法签名,这个方法在一个声明为FunctionalInterface的接口里,并且它是接口里唯一的方法。在我们的java框架里,很多地方在用函数式接口,下面的线程类的部分代码事实上,在外部需要使用Runnable的实例时,可以直接构建一个匿名对象,像下面的代码是合法的

函数式接口

就是在 java 8里允许你为一个接口(只有一个实现的,声明为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();
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Design in a Nutshell

Web Design in a Nutshell

Jennifer Niederst / O'Reilly Media, Inc. / 2006-02-21 / USD 34.99

Are you still designing web sites like it's 1999? If so, you're in for a surprise. Since the last edition of this book appeared five years ago, there has been a major climate change with regard to web......一起来看看 《Web Design in a Nutshell》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换