Java Lambda Expressions - Single Method Interface
자바8 람다 표현식은 컴파일 시에 인터페이스의 형식을 보고 추정(Inference)하여 기동된다.
public interface StateChangeListener { public void onStateChange(State oldState, State newState); }
stateOwner.addStateListener(new StateChangeListener() { public void onStateChange(State oldState, State newState) { // do something with the old and new state. } });
stateOwner.addStateListener(
(oldState, newState) -> System.out.println("State changed")
);
때로는 반환값이 필요할 때가 있는데,
(param) -> {
System.out.println("param: " + param);
return "return value";
}
인터페이스 구현체를 객체로 사용할 수도 있다
public interface MyComparator { public boolean compare(int a1, int a2); }
MyComparator myComparator = (a1, a2) -> return a1 > a2; boolean result = myComparator.compare(2, 5);
'프로그래밍 > java' 카테고리의 다른 글
Jenkov.com - Java Enum & Annotation (0) | 2015.04.24 |
---|---|
Jenkov.com - Java Interfaces (0) | 2015.04.21 |
Jenkov.com - Java Abstract Class (0) | 2015.04.21 |