搜尋此網誌

2015年6月21日 星期日

Java 8 新功能概述

Default Methods


以前如果為interface加入新的方法, 那麼所有的實作類別都必須要實作這個新方法.

有了default method這個功能後, 只要在新方法前面加上default關鍵字,然後實做它的內容.

那麼那些之前的實作類別, 也都可以使用這個新方法, 而不必自己實作. 範例如下:

package lang;

public class DefaultMethodDemo {

 public static void main(String[] args){
  
  new Client().run();
  new Client().runDefault();
  
 }
}

interface Run {
 public void run();
 default void runDefault(){
  System.out.println("default run .");
 }
}

class Client implements Run {

 @Override
 public void run() {
  System.out.println("client run .");
 }
 
}

Type Annotaion

Java 8之前, Annotaion只能用在宣告上 , 例如宣告類別, 或是宣告方法 , 或是宣告變數.

而Java 8對於 Annotaion的支援範圍擴大到 , 只要有使用到type的地方, 都可以使用Annotaion.

  1. 型別創建的時候 
    
    new @Interned MyObject();
  2. 轉型的時候
    myString = (@NonNull String) str;
3. implements 子句時:
          
class UnmodifiableList implements
        @Readonly List<@Readonly T> { ... }

4. 丟出例外的宣告:
void monitorTemperature() throws
        @Critical TemperatureException { ... }




Repeating Annotations.

Java 8 可以在同一個宣告上, 重複使用同一種Annotation.

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

代表這個method, 有兩種不同的的排程 , 分別用同一種Annotation,賦予不同值來表示.



Java Lambda 簡單介紹.

Lambda 是Java 8 支援的新功能 . 對於簡化functional interface的實作很方便. 所謂的functional

interface就是只有一個public method的interface. 下面是範例.


package lang;

public class LambdaDemo {

 public static void main(String[] args) {
  LambdaDemo ld = new LambdaDemo();
  
  /**
   * Using Lambda
   */
  ld.lambdaTest(t -> {
   System.out.println("a lambda run");
  });
  
  /**
   * Without using Lambda
   */
  ld.lambdaTest(new Test(){

   @Override
   public void run(Test t) {
    System.out.println("not a lambda run");
   }
   
  });
 }

 public void lambdaTest(Test t) {
  t.run(t);
 }

}

interface Test {
 public void run(Test t);
}

以前必須要把run()的method signature寫一遍,然後裡面是實作,有了Lambda之後, 諸如此類的實作就可以大幅簡化了.