0Pricing
Java Academy · 강의

정적 메서드 참조

정적 메서드를 호출하는 람다를 ClassName::methodName 참조로 바꿉니다.

정적 메서드 참조은(는) CoddyKit의 무료 Java Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Java Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

메서드 참조란 무엇인가요?

메서드 참조는 기존 메서드에 작업을 위임하는 람다의 축약형입니다. 람다가 단일 메서드만 호출하는 경우 메서드 참조를 사용하면 더 간결하고 읽기 쉽습니다.

import java.util.*;
import java.util.stream.*;

List<String> names = List.of("Alice", "Bob", "Carol");

// Lambda:
names.forEach(s -> System.out.println(s));

// Equivalent method reference:
names.forEach(System.out::println);

정적 메서드 참조 문법

정적 메서드 참조의 형식은 ClassName::staticMethodName입니다. 함수형 인터페이스가 동일한 시그니처의 메서드를 요구하는 모든 곳에서 사용할 수 있습니다.

import java.util.stream.*;

// Integer.parseInt(String) matches Function<String, Integer>
List<String> strs = List.of("1","2","3","4","5");
List<Integer> nums = strs.stream()
    .map(Integer::parseInt)  // replaces s -> Integer.parseInt(s)
    .collect(Collectors.toList());
System.out.println(nums); // [1, 2, 3, 4, 5]

메서드 참조로 사용하는 Math.abs

Math와 같은 유틸리티 클래스의 정적 메서드는 직접 참조할 수 있습니다:

import java.util.*;
import java.util.stream.*;

List<Integer> values = List.of(-3, 5, -1, 8, -4);
List<Integer> abs = values.stream()
    .map(Math::abs)  // replaces v -> Math.abs(v)
    .collect(Collectors.toList());
System.out.println(abs); // [3, 5, 1, 8, 4]

Predicate와 함께 사용하는 정적 메서드 참조

불리언을 반환하는 조건에 맞는 정적 메서드는 Predicate로 사용할 수 있습니다:

import java.util.stream.*;

// String.isEmpty() is an instance method, but we can use a static helper
// Objects.isNull matches Predicate<Object>
List<String> mixed = Arrays.asList("hello", null, "world", null);
long nullCount = mixed.stream()
    .filter(Objects::isNull)
    .count();
System.out.println(nullCount); // 2

long nonNull = mixed.stream()
    .filter(Objects::nonNull)
    .count();
System.out.println(nonNull); // 2

Comparator 정적 참조

Comparator에 맞는 정적 메서드도 참조할 수 있습니다:

import java.util.*;
import java.util.stream.*;

List<String> words = List.of("banana", "apple", "cherry");

// String.CASE_INSENSITIVE_ORDER is a Comparator
List<String> sorted = words.stream()
    .sorted(String::compareToIgnoreCase)
    .collect(Collectors.toList());
System.out.println(sorted); // [apple, banana, cherry]

사용자 지정 정적 helper 메서드

정적 유틸리티 메서드를 정의하고 직접 참조합니다:

class Validator {
    static boolean isPositive(int n) { return n > 0; }
    static String toLabel(int n) { return n > 0 ? "POS" : "NEG"; }
}

List<Integer> nums = List.of(-2, 3, -1, 5, 0);

List<Integer> positive = nums.stream()
    .filter(Validator::isPositive)
    .collect(Collectors.toList());
System.out.println(positive); // [3, 5]

List<String> labels = nums.stream()
    .map(Validator::toLabel)
    .collect(Collectors.toList());

정적 메서드와 함께 사용하는 BiFunction

두 매개변수를 받는 정적 메서드는 BiFunction<T,U,R>에 맞출 수 있습니다:

import java.util.function.*;

// Math.max(int,int) → BiFunction... but needs IntBinaryOperator
java.util.function.IntBinaryOperator maxOp = Math::max;
System.out.println(maxOp.applyAsInt(7, 3)); // 7

// String.format as BiFunction? Only works if signature matches:
// Integer.sum(int,int) → IntBinaryOperator
java.util.function.IntBinaryOperator sum = Integer::sum;
System.out.println(sum.applyAsInt(10, 20)); // 30

Comparator.comparing과 정적 참조로 정렬하기

깔끔하게 정렬하려면 Comparator.comparing을 메서드 참조와 결합합니다:

record Person(String name, int age) {}
List<Person> people = List.of(
    new Person("Charlie",30), new Person("Alice",25), new Person("Bob",35)
);

people.stream()
    .sorted(Comparator.comparing(Person::name))
    .forEach(p -> System.out.println(p.name()));
// Alice, Bob, Charlie

정적 메서드 참조를 사용하는 경우

다음과 같은 경우 정적 메서드 참조를 사용합니다:

  • 람다 본문이 하나의 정적 메서드 호출인 경우
  • 인수를 변환할 필요가 없는 경우
  • 메서드 시그니처가 함수형 인터페이스와 일치하는 경우

인수를 변환하거나 로직을 추가해야 한다면 람다를 사용하십시오.

가독성 비교

람다와 메서드 참조 방식을 나란히 비교합니다:

// Lambda style
Stream.of("1","2","3").map(s -> Integer.parseInt(s));
Stream.of(1,-2,3).filter(n -> n > 0);
Stream.of(-5,2,-1).map(n -> Math.abs(n));

// Method reference style
Stream.of("1","2","3").map(Integer::parseInt);
Stream.of(1,-2,3).filter(Validator::isPositive);
Stream.of(-5,2,-1).map(Math::abs);

흔한 함정: 잘못된 시그니처

메서드 참조는 해당 시그니처가 함수형 인터페이스의 추상 메서드와 정확히 일치할 때만 작동합니다. 인수의 유형이나 개수가 다르면 람다 래퍼를 대신 사용하십시오.

// Math.pow(double, double) needs two args — can't use as Function<Double, Double>
// This won't compile:
// Function<Double, Double> square = Math::pow; // ERROR

// Fix with lambda:
Function<Double, Double> square = n -> Math.pow(n, 2);
System.out.println(square.apply(5.0)); // 25.0

빠른 확인

다음 중 Predicate<Object>로 사용할 수 있는 유효한 정적 메서드 참조는 무엇입니까?

복습: 정적 메서드 참조

핵심 내용:

  • 문법: ClassName::staticMethodName
  • 단일 정적 메서드에 작업을 위임하는 람다를 대체합니다
  • 메서드 시그니처가 함수형 인터페이스의 추상 메서드와 일치해야 합니다
  • Predicate, Function, Consumer, Comparator 등과 함께 사용할 수 있습니다
  • 인수 변환이나 추가 로직이 필요하면 람다를 사용합니다

자주 묻는 질문

“정적 메서드 참조” 강의는 무료인가요?

네 — “정적 메서드 참조” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Java Academy 강의 전체를 잠금 해제할 수 있습니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“정적 메서드 참조”에서 뭘 배우나요?

정적 메서드를 호출하는 람다를 ClassName::methodName 참조로 바꿉니다. 브라우저에서 직접 실행하는 실습 코드로 Java Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Java Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Java Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“정적 메서드 참조” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Java Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Java Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 정적 메서드 참조
  2. 특정 인스턴스의 인스턴스 메서드 참조
  3. 임의 인스턴스 메서드 참조
  4. 생성자 참조
← Java Academy(으)로 돌아가기