没有参数和返回值的 Java 8 函数式接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23868733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:42:54  来源:igfitidea点击:

Java 8 functional interface with no arguments and no return value

javajava-8java-stream

提问by Miguel Gamboa

What is the Java 8 functional interface for a method that takes nothing and returns nothing?

什么是 Java 8 函数式接口,它不接受任何内容也不返回任何内容?

I.e., the equivalent to to the C# parameterless Actionwith voidreturn type?

即,相当于 C# 无参数Actionvoid返回类型?

采纳答案by assylias

If I understand correctly you want a functional interface with a method void m(). In which case you can simply use a Runnable.

如果我理解正确,您需要一个带有方法的功能接口void m()。在这种情况下,您可以简单地使用Runnable.

回答by Charana

Just make your own

只做你自己的

@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();
        };
    }
}

and use it like this

并像这样使用它

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();

}

and the output

和输出

HelloWorld
WorldHello

回答by uma mahesh

@FunctionalInterface allows only method abstract method Hence you can instantiate that interface with lambda expression as below and you can access the interface members

@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:::