5

Lambda Java 8(Oracle JDK)中有趣的编译错误

java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

我有一个方法调用:

new CSVFile()
.of(new FileInputStream("MyFile.csv"))
.withColumnMapping("name", "fullName", s -> s.toUpperCase())
.withColumnMapping("gender", "gender", s -> s.toUpperCase());

这是我试图调用的方法:

 public CSVFile withColumnMapping(final String columnName, final String   beanPropertyName, final Function<String, Object> columnTransformFunction) {
    columnMappings.add(new ColumnMapping(columnName, beanPropertyName, Optional.of(columnTransformFunction)));
    return this;
}

我得到的编译错误是:

[ERROR] /Users/sai/fun/reactivecsv/src/test/java/reactivecsv/CSVFileTest.java:[26,50] cannot find symbol
[ERROR] symbol:   method toUpperCase()
[ERROR] location: variable s of type java.lang.Object

奇怪的是,这编译

Function<String, Object> upperCaseConversion = String::toUpperCase;
new CSVFile()
.of(new FileInputStream("MyFile.csv"))
.withColumnMapping("name", "fullName", upperCaseConversion)
.withColumnMapping("gender", "gender", upperCaseConversion);

为什么编译器无法将 lambda 合成为 Function ?

4

1 回答 1

8

当您new CSVFile()为泛型类型创建时,它变成了原始类型。您不得使用原始类型。将其创建为原始类型也会将其所有方法更改为原始方法,因此无法推断出您的 lambda 参数的类型withColumnMapping(String, String, Function<String, Object>)withColumnMapping(String, String, Function)要解决您的问题,请在调用构造函数时指定正确的泛型参数。

于 2015-07-29T10:56:53.573 回答