简体   繁体   中英

Using method reference to call static methods

I am trying to understand the concept of Method references. When trying out different calls, I stumbled upon a scenario which I cant fully understand.

When canClim is used without a parameter, it can be passed to forEach without problems although forEach takes a Consumer which should take in a parameter? When adding a parameter to canClim it prevents compiling?

However when canClim is declared as static it won't compile without adding static void canClim(Animal a) to the signature. Shouldn't it be possible to call the static method without having a instance of the Animal class because it is static ?

Thanks!

import java.util.*;

class Animal {
    void canClim() {
        System.out.println("I am a climber!");
    }
}

public class MethodReferencer {
    public static void main(String[] args) {
        Animal a = new Animal();
        Animal b = new Animal();
        List<Animal> list = new ArrayList<>(Arrays.asList(a, b));
        list.forEach(Animal::canClim);

    }
}

When the method is non-static,

Animal::canClim
is equivalent to
animal -> animal.canClim()
or (animal) -> animal.canClim()

The animal on the left side of the lambda is the consumer function parameter, and the body is on the right. So yes, you are supplying a consumer there.

Static methods behaves a bit differently.
For example, Integer::parseInt would become str -> Integer.parseInt(str) .
Basically the parameter is supplied to the parameter of the method. So in static methods, you need to have a parameter to be able to use method references.

The Consumer has a method accept that takes an argument. A static method with no argument couldn't be converted to a Consumer , could it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM