中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

java8的函數式接(jie)口

函數式接口

就是(shi)在java8里允許你為(wei)一(yi)(yi)個(ge)接口(kou)(只有一(yi)(yi)個(ge)實(shi)現(xian)的,聲(sheng)明為(wei)FunctionalInterface注解的)實(shi)現(xian)一(yi)(yi)個(ge)匿名(ming)的對象(xiang),大叔感覺它(ta)與.net平(ping)臺的委托很類似,一(yi)(yi)個(ge)方法(fa)(fa)里允許你接收一(yi)(yi)個(ge)方法(fa)(fa)簽名(ming),這(zhe)個(ge)方法(fa)(fa)在一(yi)(yi)個(ge)聲(sheng)明為(wei)FunctionalInterface的接口(kou)里,并且(qie)它(ta)是(shi)接口(kou)里唯一(yi)(yi)的方法(fa)(fa)。

java框架里也在用它

在我(wo)們的java框架里(li),很多(duo)地方在用函數式接口(kou),下面的線程類的部(bu)分代碼

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

事實(shi)上(shang),在外部需要使(shi)用Runnable的實(shi)例時,可以直接構建一個匿名對象,像(xiang)下面的代碼是合法(fa)的

 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;

      }
    });

下面是(shi)大叔在單元測試里寫的一段實例代碼,供大家學習和參(can)考

 @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 @ 2019-03-01 17:12  張占嶺  閱讀(778)  評論(0)    收藏  舉報