I have the following code:
Map<String, ReportConfig> reportConfigMap = reportFactory.getReportConfigMap();
List<String> resultList = reportConfigMap.values()
.parallelStream()
.filter(Utility::shouldReportVisibleToUser)
.map(ReportConfig::getName)
.collect(Collectors.toList());
ReportConfig Class Code
public class ReportConfig implements Comparable<ReportConfig> {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
for the portion of code .map(ReportConfig::getName)
, I am passing the method reference of getName method using ReportConfig::getName
which looks like as if getName is static method of ReportConfig class but actually it is the non-static method of that class.
If I try to do the same thing in my custom function, then java gives error which says: Cannot make a static reference to the non-static method
. For example following code will not work:
public class Test{
public static void main (String[] agrs){
Test test = new Test();
test.executeService(Test::test);
}
public static ReportConfig executeService(Function<? extends ReportConfig,? extends ReportConfig> mapper){
return mapper.apply(null);
}
public ReportConfig test(ReportConfig r){
return r;
}
}
My question is how it if working for map
method of stream and not working for my custom method? Is there anything I am doing wrong or I completely misunderstood something?
ReportConfig::getName
is roughly equivalent to:
public static String getName(ReportConfig arbitraryObject) {
...
}
The compiler searches the ReportConfig
class for a method that matches the above signature. Since instance methods implicitly take this
as the first parameter, the compiler finds the instance method getName()
to be applicable. Furthermore, this signature matches the type arguments of a Function<ReportConfig, String>
, so everything works fine.
On the other hand, going with the same inference as above, Test::test
would be equivalent to:
public static ReportConfig test(Test arbitraryObject, ReportConfig r) {
return r;
}
In this case, the compiler finds the method public ReportConfig test(ReportConfig r)
which matches the above signature, but which cannot be converted to a Function<? extends ReportConfig,? extends ReportConfig>
(it would be converted to a BiFunction<Test, ReportConfig, ReportConfig>
instead). Therefore the compiler resorts to finding a static test
method, which does not exist.
To make it compile, either make the test
method static, or use test::test
instead of Test::test
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments