Method reference operator
메서드 참조 연산자
자바에서 람다식을 쓰다보면 보게 되는 이 :: 는 무엇일까?
자바8에서 도입된 연산자로 메서드 참조 연산자라고도 부른다. 람다식과 동일한 역할을 하지만, 람다식과 다르게 매개변수를 작성하지 않는다는 차이점이 있다.
기본적인 람다식을 더블 콜론을 사용하여 바꾸면 이렇게 된다.
// lambda
(a, b) -> ClassName.methodName(a, b)
// double colon
className::methodName
::을 이용해 static 메서드를 호출할 수 있다.
ClassName::staticMethod
...
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Taylor");
list.add("Swift");
// lambda로 호출
list.forEach(s -> Call.someFuntion(s));
// 더블 콜론으로 호출
list.forEach(Call::someFunction);
}
...
class Call {
// static function to be called
static void someFunction(String s) {
System.out.println(s);
}
}
objectName::instanceMethod 구문을 통해 인스턴스 메서드를 호출할 수 있다.
...
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Taylor");
list.add("Swift");
Call call = new Call();
// lambda로 호출
list.forEach(s -> call.someFuntion(s));
// 더블 콜론으로 호출
list.forEach(call::someFunction);
// 이렇게도 가능하다
list.forEach((new Call())::someFunction);
}
...
class Call {
// instance method to be called
void someFunction(String s) {
System.out.println(s);
}
}
class Test {
String str=null;
Test(String s) {
this.str=s;
}
// instance function to be called
void someFunction() {
System.out.println(this.str);
}
}
class Taylor {
public static void main(String[] args)
{
List<Test> list = new ArrayList<Test>();
list.add(new Test("Taylor"));
list.add(new Test("Swift"));
list.forEach(Test::someFunction);
}
}
원래는 (a, b) -> {return new ClassName(a, b)} 이렇게 되야할 구문도 더블 콜론을 사용하여 ClassName::new 이런 식으로 사용할 수 있다.
class Taylor {
// Class constructor
public Call(String s) {
System.out.println("Hello " + s);
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Taylor");
list.add("Swift");
// call the class constructor
list.forEach(Call::new);
}
}
더블 콜론을 사용해 super 메서드도 호출할 수 있다.
class Test {
// super function to be called
String print(String str) {
return ("Hello " + str + "\n");
}
}
class Taylor extends Test {
// instance method to override super method
@Override
String print(String s)
{
// call the super method using double colon operator
Function<String, String>
func = super::print;
String newValue = func.apply(s);
newValue += "Bye " + s + "\n";
System.out.println(newValue);
return newValue;
}
}