2017-07-19 67 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