有时我需要从一种方法回调到另一种方法:
final Integer i = 5;
final Integer j = 10;
foo("arg1", "arg2", (x, y) -> {
/** do sth which need this context **/
bar(i + x, j - y);
})
但在这种情况下,我需要编写简单的界面(某处):
public interface someName {
void noMatterName(Integer a, Integer c);
}
然后函数 foo()
可以调用 noMatterName
- 这是可以的。但在简单的情况下,此类接口(interface)的名称及其功能并不重要。我只想使用带有两个参数的 lambda。
问题:
即使我只需要在两个函数之间进行这种“通信”,我是否需要手动创建此接口(interface)? Java有提供类似的接口(interface)吗? 或者甚至是这样的:
public interface someName1 {
void noMatterName(Object a);
}
public interface someName2 {
void noMatterName(Object a, Object b);
}
最佳答案
您可以使用Consumer<T> (如果您需要单个参数)和 BiConsumer<T,U> (如果您需要2个参数)功能接口(interface)。
Interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result.
Interface BiConsumer<T,U>
Represents an operation that accepts two input arguments and returns no result.
关于Java 8 : Interface with single method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32633943/