λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

πŸ“– Java&Spring

ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€ (Functional Interface)

Javaμ—μ„œ ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€λŠ”

단일 좔상 λ©”μ„œλ“œ(Single Abstract Method, SAM)λ₯Ό 가진 μΈν„°νŽ˜μ΄μŠ€λ‹€.

 

Java 8 μ΄μƒμ—μ„œλŠ” λžŒλ‹€ ν‘œν˜„μ‹ 및 ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€λ₯Ό μ§€μ›ν•œλ‹€.

 

ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€μ˜ 좔상 λ©”μ„œλ“œ μ‹œκ·Έλ‹ˆμ²˜λŠ” λžŒλ‹€ ν‘œν˜„μ‹κ³Ό 연관이 μžˆλ‹€.

(좔상 λ©”μ„œλ“œ μ‹œκ·Έλ‹ˆμ²˜λŠ” ν•΄λ‹Ή ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€κ°€ λ‚˜νƒ€λ‚΄λŠ” ν•¨μˆ˜μ˜ ν˜•νƒœλ₯Ό κ²°μ •ν•˜λŠ” 것)

 

java.util.function νŒ¨ν‚€μ§€μ—λŠ” λ‹€μ–‘ν•œ ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€κ°€ ν¬ν•¨λ˜μ–΄ 있음.

Consumer μΈν„°νŽ˜μ΄μŠ€μ˜ 좔상 λ©”μ„œλ“œλŠ” λ‹€μŒκ³Ό κ°™λ‹€.

 

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

 

μ—¬κΈ°μ„œ acceptκ°€ 좔상 λ©”μ„œλ“œμ΄λ‹€.

이 λ©”μ„œλ“œλŠ” ν•˜λ‚˜μ˜ λ§€κ°œλ³€μˆ˜λ₯Ό λ°›κ³  λ°˜ν™˜κ°’μ΄ μ—†μΈ°. (ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€)

μ΄λ ‡κ²Œ μ •μ˜λœ μΈν„°νŽ˜μ΄μŠ€λŠ” λžŒλ‹€ ν‘œν˜„μ‹μœΌλ‘œ ν‘œν˜„ν•  수 μžˆλ‹€.


@FunctionalInterface μ–΄λ…Έν…Œμ΄μ…˜

ν•΄λ‹Ή μΈν„°νŽ˜μ΄μŠ€κ°€ ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€μž„μ„ λ‚˜νƒ€λ‚΄λ©°, μ»΄νŒŒμΌλŸ¬κ°€ 이 κ·œμΉ™μ„ μ²΄ν¬ν•˜λ„λ‘ 함.

ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€μ˜ 좔상 λ©”μ„œλ“œ μ‹œκ·Έλ‹ˆμ²˜λ₯Ό μ•Œλ©΄

κ·Έ μΈν„°νŽ˜μ΄μŠ€λ₯Ό λžŒλ‹€ ν‘œν˜„μ‹μœΌλ‘œ ν‘œν˜„ν•  λ•Œ

ν•„μš”ν•œ λ§€κ°œλ³€μˆ˜ νƒ€μž… 및 λ°˜ν™˜ νƒ€μž…μ„ 이해할 수 있음.

 

ν•¨μˆ˜ν˜• ν”„λ‘œκ·Έλž˜λ°μ—μ„œλŠ” ν•¨μˆ˜λ₯Ό κ°’μœΌλ‘œ μ·¨κΈ‰ν•˜κ³ , μ΄λŸ¬ν•œ 값은 ν•΄λ‹Ή ν•¨μˆ˜μ˜ μ‹œκ·Έλ‹ˆμ²˜μ— 따라 λ™μž‘ν•œλ‹€λŠ₯.

 

@FunctionvalInterface μ–΄λ…Έν…Œμ΄μ…˜μ— λŒ€ν•΄ μžλ°” 곡식 λ¬Έμ„œ λ‚΄μš©μ„ μ’€ 더 닀뀄보겠닀.

 

Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

 

핡심은 ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€λŠ” 단 ν•˜λ‚˜μ˜ 좔상 λ©”μ„œλ“œλ§Œ κ°€μ Έμ•Ό ν•œλ‹€.

즉, κΈ°λ³Έ λ©”μ„œλ“œλŠ” μ˜€λ²„λΌμ΄λ”©ν•œ 것을 ν¬ν•¨ν•˜μ—¬ ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€ λ‚΄μ—μ„œ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€.

그리고 java.lang.Object에 κ΅¬ν˜„λœ λ‹€λ₯Έ μΈν„°νŽ˜μ΄μŠ€λ„ μ‚¬μš© κ°€λŠ₯ν•˜λ‹€.

μ™œλƒλ©΄, μ–΄λ”˜κ°€μ—λŠ” κ΅¬ν˜„λ˜μ–΄ 있기 λ•Œλ¬Έμ΄μž–μŠ΄~