Search code examples
java-8java-streammethod-referenceassertj

When do method references work?


Method references don't work with non-static methods AFAIK. I tried using them in the following way

Arrays.stream(new Integer[] {12,321,312}).map(Integer::toString).forEach(System.out::println);

Which resulted in the compilation error as seen in the link.

Picture for error

Problem
While using AssertJ library, I used something like this,

AbstractObjectAssert<?, Feed> abstractObjectAssertFeed2 = assertThat(feedList.get(2));
abstractObjectAssertFeed2.extracting(Feed::getText).isEqualTo(new Object[] {Constants.WISH+" HappyLife"});

where Feed is a noun and getText is a getter method and not static, but it worked fine without compilation error or any error which puzzled me.

Proof not a static method.

Am I missing something about how method references work?


Solution

  • This is invalid for a different reason.

    Basically there are two toString implementations in Integer.

    static toString(int)
    

    and

    /*non- static*/ toString()
    

    Meaning you could write your stream like this:

     Arrays.stream(new Integer[] { 12, 321, 312 })
           .map(i -> i.toString(i))
           .forEach(System.out::println);
    
    Arrays.stream(new Integer[] { 12, 321, 312 })
           .map(i -> i.toString())
           .forEach(System.out::println);
    

    Both of these qualify as a method reference via Integer::toString. The first one is a method reference to a static method. And the second is Reference to an instance method of an arbitrary object of a particular type.

    Since they both qualify the compiler does not know which to choose.