2016-12-05 79 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