2016-12-05 43 views
1

我目前工作我的方式深入Java核心的書,我在通用章。在這裏我無法掌握一件事。正如書中指出,你不能讓一個新的對象了T的泛型類,所以這是不可能的與拉姆達的Java通用對象表達式

public foo() { first = new T(); second = new T(); } //ERROR 

你可以做的是使用功能接口和lambda表達式參考構造器,這樣

foo<String> f = foo.makeFoo(String::new) 

​​

,它的偉大,工作正常,但只有字符串,如果我想與任何其他目的使用,例如包裝簡單類型整數這是不可能的。它給了我這個錯誤

Error:(35, 38) java: method makeFoo in class generic.foo<T> cannot be applied to given types; 
required: java.util.function.Supplier<T> 
found: Integer::new 
reason: cannot infer type-variable(s) T 
(argument mismatch; incompatible parameter types in method reference) 

看來只能用字符串工作,我不知道爲什麼,我認爲它會工作的每個對象

我試圖創建正確的類中的所有這些對象

foo<String> fString = foo.makeFoo(String::new); //Works 
    foo<Integer> fInteger = foo.makeFoo(Integer::new); //Doesn't work 
    foo<Double> fDouble = foo.makeFoo(Double::new); //Doesn't work 

編輯

其實這個作品與自定義對象,鄰NLY包裝簡單類型不會編譯

foo<MyCustomObject> fCustom = foo.makeFoo(MyCustomObject::new); //Works 
+1

變量類型'F'的是'富',所以很明顯,預計在供應商返回'String'對象。如果你給它一個返回一個'Integer'對象的供應商,把它改爲'foo '。 – Jesper

+0

我正在那樣做,這給不能應用錯誤。 foo fInteger = foo.makeFoo(Integer :: new); –

+1

@MTomczyński我已經拒絕了你對我的答案的編輯,因爲我寫了很多文本/代碼。我認爲如果你將它作爲你自己的問題答案發佈會更好,這是絕對合適的。 – lexicore

回答

3

相反String,存在Integer沒有無參數的構造函數。所以Integer::new不是Supplier<Integer>makeFoo(Object::new)會工作。

1

正如lexicore所指出的,我們無法表達Integer :: new,因爲Integer對象沒有無參數構造函數。與整數正確的語法可以是如此簡單,其中Arg爲int變量

foo<Integer> f = foo.makeFoo(() -> (arg)); 

在新的整數(ARG)包裝是不必要在這裏。

的話題更多信息:Java 8 Supplier with arguments in the constructor