我有一个类有几个返回相同类型的方法.所以,例如,我有以下对象定义:
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)
您需要一个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)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |