JAVA 메서드 참조

김개발세발바닥·2024년 7월 14일

JAVA

목록 보기
9/12

메서드 참조.

Java에서 메서드 참조는 람다 표현식을 간결하게 표현하기 위한 문법이다.
메서드 참조는 메서드의 이름을 참조함으로써, 람다 표현식보다 가독성을 높이고 코드의 간결성을 향상시킨다.

정적 메서드 참조.

정적 메서드는 클래스에 속하는 메서드로, 객체 생성 없이 호출할 수 있다.
메서드 참조는 클래스명::메서드명 형식으로 작성한다.

import java.util.function.Function;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // 람다 표현식
        Function<String, Integer> lambdaFunction = s -> Integer.parseInt(s);
        
        // 메서드 참조
        Function<String, Integer> methodRefFunction = Integer::parseInt;
        
        // 사용 예
        Integer result = methodRefFunction.apply("123");
        System.out.println(result); // 123
    }
}

인스턴스 메서드 참조.

인스턴스 메서드는 특정 객체의 메서드를 참조한다.
메서드 참조는 클래스명::메서드명 형식으로 작성하며, 이 때 첫 번째 파라미터는 메서드를 호출할 인스턴스다.

import java.util.Arrays;

public class MethodReferenceExample {
    public static void main(String[] args) {
        String[] strings = { "apple", "banana", "cherry" };
        
        // 람다 표현식
        Arrays.sort(strings, (s1, s2) -> s1.compareToIgnoreCase(s2));
        
        // 메서드 참조
        Arrays.sort(strings, String::compareToIgnoreCase);
        
        for (String s : strings) {
            System.out.println(s);
        }
    }
}

특정 객체의 인스턴스 메서드 참조.

특정 객체의 메서드를 참조할 때 사용한다.
메서드 참조는 특정객체::메서드명 형식으로 작성한다.

import java.util.function.Consumer;

public class MethodReferenceExample {
    public void instanceMethod(String s) {
        System.out.println(s);
    }
    
    public static void main(String[] args) {
        MethodReferenceExample example = new MethodReferenceExample();
        
        // 람다 표현식
        Consumer<String> lambdaConsumer = s -> example.instanceMethod(s);
        
        // 메서드 참조
        Consumer<String> methodRefConsumer = example::instanceMethod;
        
        methodRefConsumer.accept("Hello, world!");
    }
}

생성자 참조.

생성자를 참조할 때 사용합니다. 메서드 참조는 클래스명::new 형식으로 작성한다.

import java.util.function.Supplier;

public class MethodReferenceExample {
    private String message;
    
    public MethodReferenceExample() {
        this.message = "Hello";
    }
    
    public String getMessage() {
        return message;
    }
    
    public static void main(String[] args) {
        // 람다 표현식
        Supplier<MethodReferenceExample> lambdaSupplier = () -> new MethodReferenceExample();
        
        // 생성자 참조
        Supplier<MethodReferenceExample> constructorRefSupplier = MethodReferenceExample::new;
        
        MethodReferenceExample example = constructorRefSupplier.get();
        System.out.println(example.getMessage()); // Hello
    }
}

이런걸 공부하면 나의 코드가 조금 진부하다고 느껴진다...
이렇게 코드를 짤 수 있게 신경써야겠다.

0개의 댓글