Java

[Java] 람다식 / 함수형 인터페이스 / @FunctionalInterface

bkuk 2023. 3. 24. 20:40

함수형 인터페이스

 

@FunctionalInterface: 일반적으로 구현해야 할 추상 메서드가 하나만 정의된 인터페이스를 가르킨다. 자바 컴파일러는 이렇게 명시된 함수형 인터페이스에 두 개 이상의 메서드가 선언되면 에러를 발생시킨다.

@FunctionalInterface		//구현해야 할 메소드가 한개이므로 Functional Interface이다.
public interface Math {
    public int Calc(int first, int second);
}

@FunctionalInterface		//구현해야 할 메소드가 두개이므로 Functional Interface가 아니다. (오류 사항)
public interface Math {
    public int Calc(int first, int second);
    public int Calc2(int first, int second);
}

 


함수형 인터페이스 사용 예

 

함수형 인터페이스 선언

 

public interface PreparedStatementSetter {
	void setValues(PreparedStatement pstmt) throws SQLException;
}

 

함수형 인터페이스 사용

PreparedStatementSetter pstmt = new PreparedStatementSetter() {
    @Override
    public void setValues(PreparedStatement pstmt) throws SQLException {
        for (int i = 0; i < parameters.length; i++) {
            pstmt.setObject(i + 1, parameters[i]);
        }
    }
};