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();
  }

猜你喜欢

转载自www.cnblogs.com/lori/p/10457563.html