1

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?

Tarun Maganti
  • 3,076
  • 2
  • 35
  • 64
  • You don't really need to map an `Integer` to `String` if you want to print stream content. `Arrays.stream(new Integer[] {12,321,312}).forEach(System.out::println);` works fine. – Anton Balaniuc Apr 11 '17 at 11:49
  • and you can just use `.map(Object::toString)` instead of `.map(Integer::toString)` – Anton Balaniuc Apr 11 '17 at 11:50
  • @AntonBalaniuc It was a test. I was prototyping to confirm how method references work and unfortunately (or is it really) faced this problem (which I thought was real) with error message I expected. What are the odds! – Tarun Maganti Apr 11 '17 at 11:54
  • @AntonBalaniuc should I still say that question which you marked solved my problem when I didn't face the same problem and it turned out to be same? – Tarun Maganti Apr 11 '17 at 11:56
  • You should not ignore the “**2 errors**” footer line, which indicates that you ignored another error upfront. Generally, with the current compiler, if you see two error messages, “non-static method … cannot be referenced from a static context” and another error, focus on “another error” first. It’ll save you a lot of time. – Holger Apr 13 '17 at 12:01

1 Answers1

2

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.

Eugene
  • 117,005
  • 15
  • 201
  • 306