programing

인수 및 반환값이 없는 Java 8 기능 인터페이스

bestcode 2022. 10. 7. 22:31
반응형

인수 및 반환값이 없는 Java 8 기능 인터페이스

아무것도 받지 않고 아무것도 반환하지 않는 메서드의 Java 8 기능 인터페이스는 무엇입니까?

즉, C# 파라미터리스에 상당합니다.Action와 함께void리턴 타입?

내가 제대로 이해했다면, 당신은 어떤 방식의 기능적인 인터페이스를 원합니까?void m()이 경우 를 사용할 수 있습니다.

나만의 것을 만들어라

@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

@FunctionalInterface메서드 추상 메서드만 허용하기 때문에 다음과 같이 람다 식을 사용하여 인터페이스를 인스턴스화할 수 있으며 인터페이스 멤버에 액세스할 수 있습니다.

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

출력:

i am log method:::lets do it.
i m1 method:::

언급URL : https://stackoverflow.com/questions/23868733/java-8-functional-interface-with-no-arguments-and-no-return-value

반응형