什么是Java 8功能接口,什么是什么都没有,什么也没有返回?
即,相当于带有Action
返回类型的C#无参数void
?
答案 0 :(得分:82)
如果我理解正确,你想要一个方法void m()
的功能界面。在这种情况下,您只需使用Runnable
。
答案 1 :(得分:7)
制作自己的
@FunctionalInterface
public interface Procedure {
void run();
default Procedure andThen(Procedure after){
return () -> {
this.run();
after.run();
};
}
default Procedure compose(Procedure before){
return () -> {
before.run();
this.run();
};
}
}
并像这样使用
public static void main(String[] args){
Procedure procedure1 = () -> System.out.print("Hello");
Procedure procedure2 = () -> System.out.print("World");
procedure1.andThen(procedure2).run();
System.out.println();
procedure1.compose(procedure2).run();
}
和输出
HelloWorld
WorldHello
答案 2 :(得分:0)
@FunctionalInterface仅允许方法抽象方法,因此您可以使用如下所示的lambda表达式实例化该接口,并可以访问接口成员
@FunctionalInterface
interface Hai {
void m2();
static void m1() {
System.out.println("i m1 method:::");
}
default void log(String str) {
System.out.println("i am log method:::" + str);
}
}
public class Hello {
public static void main(String[] args) {
Hai hai = () -> {};
hai.log("lets do it.");
Hai.m1();
}
}
output:
i am log method:::lets do it.
i m1 method:::