Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a reference to an instance method in Java 8

Tags:

java-8

I have a class which has several methods returning the same type. So, for example, I have the following object definition:

interface MyClass {
  String first();
  String second();
}

Then I have a method, which accepts a list of objects of this class, and should call either first() or second() method depending on the parameter. An example:

void myMethod(List<MyClass> objs, boolean executeFirst) {
    objs.forEach(obj -> System.out.println(executeFirst ? obj.first() : obj.second()));
}

Is there any way of replacing the executeFirst parameter with a reference to and instance method, which I want to execute on the objs object? So, for example, ideally I'd like to have something like this:

void myMethod(List<MyClass> objs, Supplier<String> instanceMethod) {
    objs.forEach(obj -> System.out.println(obj::instanceMethod.get());
}
like image 279
rmaruszewski Avatar asked Jun 14 '26 13:06

rmaruszewski


1 Answers

You need a Function<MyClass, String>, not a Supplier:

public void foo() {
    myMethod(someList, MyClass::first);
}

void myMethod(List<MyClass> objs, Function<MyClass, String> instanceMethod) {
    objs.forEach(obj -> System.out.println(instanceMethod.apply(obj));
}
like image 196
JB Nizet Avatar answered Jun 18 '26 01:06

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!