我目前工作我的方式深入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
变量类型'F'的是'富',所以很明显,预计在供应商返回'String'对象。如果你给它一个返回一个'Integer'对象的供应商,把它改为'foo '。 –
Jesper
我正在那样做,这给不能应用错误。 foo fInteger = foo.makeFoo(Integer :: new); –
@MTomczyński我已经拒绝了你对我的答案的编辑,因为我写了很多文本/代码。我认为如果你将它作为你自己的问题答案发布会更好,这是绝对合适的。 – lexicore