[Java] Double colon (::) 연산자

코딩하는 꽁지·2024년 3월 16일
post-thumbnail

Double colon(::) operator in Java

Method reference operator
메서드 참조 연산자

자바에서 람다식을 쓰다보면 보게 되는 이 :: 는 무엇일까?

자바8에서 도입된 연산자로 메서드 참조 연산자라고도 부른다. 람다식과 동일한 역할을 하지만, 람다식과 다르게 매개변수를 작성하지 않는다는 차이점이 있다.

기본적인 람다식을 더블 콜론을 사용하여 바꾸면 이렇게 된다.

// lambda
(a, b) -> ClassName.methodName(a, b)
// double colon
className::methodName

✅ 더블 콜론(::)을 쓸 수 있는 경우

▪︎ static 메서드 참조

::을 이용해 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 메서드 참조

더블 콜론을 사용해 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; 
    } 
}

📚 Reference

profile
프로그래밍으로 온 세상을 떠들썩 하게~🪼

0개의 댓글