0

I am working with reflection and I noticed unexpected methods. I completely narrowed it down to just these few lines of code which reproduces the problem:

import java.lang.reflect.Method;
import java.util.Arrays;

class Scratch {
    void someMethod() {
        // Yea yea, useless code but it's just for demonstration!
        Arrays.stream(new Integer[] { 0 }).toArray(Integer[]::new);
    }

    public static void main(String[] args) {
        for (Method method: Scratch.class.getDeclaredMethods()) {
            System.out.println(method);   
        }
    }
}

I am asking the JVM to give me all the declared methods. I expect to see 2 methods: main and someMethod(). But I see another one:

private static java.lang.Integer[] Scratch.lambda$someMethod$0(int)

If I remove the one and only line inside someMethod, I only get 2 methods as a result of calling getDeclaredMethods, as I would expect.

What is this lamba method? I can not call it directly on Scratch, the static method isn't available (Integer[] result = Scratch.lambda$someMethod$0(0);). Is it some private method? The docs on getDeclaredMethods() does not say anything about this behavior.

I am compiling with Java 8.

J. Doe
  • 12,159
  • 9
  • 60
  • 114

1 Answers1

2

Look at the signature of the stream.toArray method:

toArray(IntFunction<A> generator)

Scratch.lambda$someMethod$0(int) is simply the lambda expression you're passing as argument to the stream.toArray method.

Imaguest
  • 379
  • 3
  • 10
  • If a method reference (translated to a lambda) generates a `private static` method, then why the following code: `Arrays.stream(Main.class.getDeclaredMethods()).forEach(System.out::println);` doesn't generate one for `System.out::println`? It's, after all, effectively a lambda that calls `System.out.println`. What's there so different than a lambda, which effectively calls `new Integer[]`? – Fureeish Oct 15 '19 at 18:05
  • In this example you call getDeclaredMethods() before the evaluation of the lambda passed into the foreach. Did you try to replace your toArray(Integer[]::new) by a foreach (with a dummy lambda, just to try if getDeclaredMethods will show it)? – Imaguest Oct 16 '19 at 07:44
  • I am not the OP, but the location of `System.out::println` changes nothing. Simple method reference not always results in a generated function. I'll try to inspect it and come up with an answer, but yours does not cover all the cases. – Fureeish Oct 16 '19 at 19:23