在Java 8中传递对实例方法的引用

rma*_*ski 3 java-8

我有一个类有几个返回相同类型的方法.所以,例如,我有以下对象定义:

interface MyClass {
  String first();
  String second();
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个方法,它接受这个类的对象列表,并应根据参数调用其中一个first()second()方法.一个例子:

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

有没有办法用executeFirst参数和实例方法替换参数,我想在objs对象上执行?所以,例如,理想情况下我想要这样的东西:

void myMethod(List<MyClass> objs, Supplier<String> instanceMethod) {
    objs.forEach(obj -> System.out.println(obj::instanceMethod.get());
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

您需要一个Function<MyClass, String>而不是供应商:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • FGITW!我刚要发布`objs.stream().map(instanceMethod).forEach(System.out :: println) (3认同)
  • 当然,但我可以在晚上睡觉,希望`List` impl按顺序处理它的流. (2认同)