2014-10-21 57 views
3

我讀Java 8 book它帶有一個樣品我重現..的Java 8構造方法引用

@FunctionalInterface 
public interface Action{public void perform();} 

一個實施者

public final class ActionImpl implements Action 
{ 
    public ActionImpl() 
    { 
     System.out.println("constructor[ActionIMPL]"); 
     return; 
    }  
    @Override 
    public void perform() 
    { 
     System.out.println("perform method is called.."); 
     return; 
    }  
} 

呼叫者。

public final class MethodReferences 
{ 
    private final Action action; 
    public MethodReferences(Action action){this.action=action;return;} 
    public void execute(){System.out.println("execute->called");action.perform();System.out.println("execute->exist");return;} 
    public static void main(String[] args) 
    { 
     final MethodReferences clazz = new MethodReferences(new ActionImpl()); 
     clazz.execute(); 
     return; 
    } 
    } 

如果這就是所謂的下面是打印到輸出

constructor[ActionIMPL] 
execute->called 
perform method is called.. 
execute->exist 

一切都很好,但如果我使用方法引用不perform message方法印刷它!爲什麼這是我錯過了什麼?

如果我使用此代碼

final MethodReferences clazz = new MethodReferences(()->new ActionImpl()); 
clazz.execute(); 

或本規範

final MethodReferences clazz = new MethodReferences(ActionImpl::new); 

這是印刷

execute->called 
constructor[ActionIMPL] 
execute->exist 

Not exception or anything else is printed

任何幫助是巨大的讚賞我是使用

Java 8 1.8.25 64 bits. 

更新

對於正在學習像我這樣的球員是正確運行的代碼。

我已經創建了一個類的調用者。

,因爲我需要實現一個空的方法perform from the Action functional interface,我需要作爲參數傳遞給類的構造函數MethodReference我引用的MethodReferenceCall which is a empty constructor and i can use it.

public final class MethodReferenceCall 
{ 
    public MethodReferenceCall(){System.out.println("MethodReferenceCall class constructor called");}   
    public static void main(String[] args) 
    { 
     final MethodReferenceCall clazz = new MethodReferenceCall(); 
     final MethodReferences constructorCaller = new MethodReferences(MethodReferenceCall::new); 
     constructorCaller.execute(); 
     return; 
    } 
} 

我希望可以幫助委內瑞拉有人問候構造。

回答

5

final MethodReferences clazz = new MethodReferences(()->new ActionImpl()); 

不使用方法參考,它使用了一個λ表達式。功能界面Action

public void perform(); 

所以

()->new ActionImpl() 

被轉換爲類似的東西

new Action() { 
    public void perform() { 
     new ActionImpl(); 
    } 
} 

同樣,在

final MethodReferences clazz = new MethodReferences(ActionImpl::new); 

ActionImpl::new 

其確實使用構造函數引用,被翻譯成類似

new Action() { 
    public void perform() { 
     new ActionImpl(); 
    } 
} 

ActionImpl::new不調用new ActionImpl()。它解析爲預期類型的​​實例,其功能接口方法被實現爲調用該構造函數。

+0

能否解釋一下更簡單..抱歉 – chiperortiz 2014-10-21 23:27:25

+1

@chiperortiz方法_reference_不是方法_invocation_。而是成爲目標功能界面的主體。 – 2014-10-21 23:28:56

+4

@chiperortiz基本上,你的第一個(工作)例子創建一個新的'ActionImpl',當它的'perform'方法被調用時,它會打印一條消息。第二個例子不會創建一個新的ActionImpl。它創建一個新的對象,其類型是一個實現了「Action」的_anonymous_類。當調用該匿名類對象的'perform'方法時,其'perform'方法會創建一個新的'ActionImpl'(然後將其拋出)。 – ajb 2014-10-21 23:49:31