2017-07-19 72 views
2

我很新到Java 8,我試圖創建一個示例程序中使用lambda表達式預期輸出「測試通過」不返回用於Java 8樣品

我要打印「測試通過」時driver.getTitle()方法返回「主頁 - Safe2Pay應用程序」。

我已經實施了兩種不同的方法。方法1是正常的Java工作流程,它正確輸出控制檯中的輸出'Test Passed'。 但方法2,使用Java 8不起作用。

String expectedTitle = "Home Page - Safe2Pay Application"; 
String actualTitle = ""; 

//Approach 1 
actualTitle = driver.getTitle(); 

if (actualTitle.contentEquals(expectedTitle)) { 
    System.out.println("Test Passed"); 
} else { 
    System.out.println("Test Failed"); 
} 

//Approach 2 
//Java 8 execution 
GetTitle m =() -> { 
    if (driver.getTitle().contentEquals(expectedTitle)) 
     System.out.println("Test Passed"); 
    else 
     System.out.println("Test Failed"); 
}; 
+3

方法2只是一個函數定義,但您並未執行它。 –

+0

什麼是GetTitle? – Seelenvirtuose

+0

當你使用lambda時,你基本上保存了一個稍後調用的方法。該方法通常會使用另一種方法調用,如apply()或run()等,具體取決於您存儲方法的類型。 – ajb

回答

0

你必須聲明一個GetTitle接口並調用該接口中的方法。

public class Driver { 
    static String expectedTitle = "Home Page - Safe2Pay Application"; 
    static String actualTitle = ""; 
    public static void main(String args[]){ 

     Driver driver = new Driver(); 

     //Approach 1 
     actualTitle = getTitle(); 

     if (actualTitle.contentEquals(expectedTitle)) { 
     System.out.println("Test Passed"); 
     } else { 
     System.out.println("Test Failed"); 
     } 

     //Approach 2 
     //Java 8 execution 
     GetTitle m = (Driver dr) -> { 
     if (Driver.getTitle().contentEquals(expectedTitle)) 
      System.out.println("Test Passed"); 
     else 
      System.out.println("Test Failed"); 
     }; 

     m.operation(driver); 

    } 
    public static String getTitle(){ 
     return expectedTitle; 
    } 

    interface GetTitle { 
     void operation(Driver driver); 
    } 
} 

接口可以在類內或類外。

2

創建實例後,仍然需要調用自定義函數接口的方法。由於您沒有發佈您的GetTitle類,所以不妨給出一個關於如何使用另一個自定義功能界面工作的小例子。

// the functional interface 
@FunctionalInterface 
public static interface Operator { 
    public void operate(); 
} 

public static void main(String[] args) 
{ 
    Operator o =() -> System.out.println("test"); //here you create a class instance of Operator. 
    o.operate(); // this is how you call that method/functional interface. 

    // this is a non-lambda example which works exactually the same, but may make things a bit more clear. 

    //create new instance 
    Operator o1 = new Operator() { 
     @Override 
     public void operate() 
     { 
      System.out.println("test"); 
     } 
    }; 

    o1.operate(); //call the method. 
} 

我希望這能夠讓你足夠的瞭解功能接口是如何工作的。

+1

這可能有助於修復錯別字,以便讀者可以自行運行。 'FunctionalInterface'以大寫字母'F'開頭,並且在第2行拼寫錯誤'Operator'。 – ajb

+0

謝謝,我們將解決它。當你使用移動設備工作時出現錯別字:D – n247s

+1

不要責怪開發者,我非常喜歡製作任何鍵盤上的拼寫錯誤。 – ajb