在Java 8中使用功能接口 [英] Use of Functional Interface in Java 8
问题描述
这是Java 8中 ::(双冒号)运算符的后续问题其中Java允许您使用 ::
运算符引用方法。
This is a follow up question from :: (double colon) operator in Java 8 in which Java allows you to refer to methods using ::
operator.
是否可以提供我创建的一些自定义功能接口,并将其与 ::
运算符一起使用?怎么做?
Is it possible to provide some custom Functional Interface that I create and use it with ::
operator? And how to do it?
推荐答案
是否可以提供我创建的一些自定义功能接口,并将其与一起使用::
运营商?怎么做?
"Is it possible to provide some custom Functional Interface that I create and use it with ::
operator? And how to do it?"
这是可能的,它就像你想象的那样简单:只需用一种方法创建一个界面。你甚至不需要 @FunctionalInterface
注释;这个注释只记录你的意图并帮助在编译时检测错误,类似于 @Override
。
It is possible and it’s as easy as you could imagine: just create an interface with exactly one method. You don’t even need the @FunctionalInterface
annotation; this annotation just documents your intention and helps detecting errors at compile time similar to @Override
.
所以也许你已经已经在你的Java 8之前的项目中创建了这样的接口...
So maybe you already have created such interfaces in your pre-Java 8 projects…
class Foo {
// nothing new:
public interface FooFactory {
Foo createFoo();
}
// new in Java 8:
public static final FooFactory DEFAULT_FACTORY = Foo::new;
}
这篇关于在Java 8中使用功能接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!