Uploaded image for project: 'Clover'
  1. Clover
  2. CLOV-1606

Java8: method reference to a non-static method fails to compile

    XMLWordPrintable

Details

    • Bug
    • Resolution: Cannot Reproduce
    • Medium
    • won't fix
    • 3.2.0
    • Instrumentation
    • None

    Description

      NOT REPRODUCIBLE

      In this code sample:

      return map.entrySet().stream()
      			.collect(Collectors.toMap(
      				Map.Entry::getKey,
      				e -> e.getValue().getAverage()
      			));
      

      the Collectors.toMap() takes a "Map.Entry::getKey" method reference as input argument. However, the getKey method is not static.

      Wrapping it by Clover's lambdaInc() method leads to a compilation error like this:

          [javac]   symbol:   method lambdaInc(int,Map.Entry::getKey,int)
          [javac]   location: class __CLR4_0_22ci2cii4lxhoaj
          [javac]  Foo.java:33: error: invalid method reference
          [javac] 					__CLR4_0_22ci2cii4lxhoaj.lambdaInc(3045,Map.Entry::getKey,3046),
          [javac] 					                                           ^
          [javac]   non-static method getKey() cannot be referenced from a static context
          [javac]   where K is a type-variable:
          [javac]     K extends Object declared in interface Entry
      

      Possible workarounds ??

      1) Disable instrumentation of expression-like lambda functions (method references are treated as expression-like lambda) - use instrumentLambda="block" or "none".

      2) Wrap such method reference with ///CLOVER:OFF and ///CLOVER:ON keywords, e.g.:

      return map.entrySet().stream()
      			.collect(Collectors.toMap(
      ///CLOVER:OFF
      				Map.Entry::getKey,
      ///CLOVER:ON
      				e -> e.getValue().getAverage()
      			));
      

      3) Use a variable with a non-static method reference or change to a lambda expression.

      return map.entrySet().stream()
      			.collect(Collectors.toMap(
      				e -> e.getKey(), // unfortunately IDEA suggests to change it back
      				e -> e.getValue().getAverage()
      			));
      

      Attachments

        Activity

          People

            mparfianowicz Marek Parfianowicz
            mparfianowicz Marek Parfianowicz
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: