JAVA/JAVA8
메소드 참조 & 생성자 참조
최-코드
2024. 8. 13. 23:34
메소드 참조
- 주 목적은 함수형 인터페이스의 구현을 단순화하기 위함이다. 람다식 표현을 간단하게 만들 수 있다.
- 문법은 '클래스이름::메서드이름'와 같다.
- ClassName::instance-methodName
- ClassName::static-methodName
- Instance::methodName
- ex) s -> s.toUpperCase() ==> String::toUpperCase
- 메소드 참조의 경우 매개변수와 다른 함수에 인자로 넣는 값이 같을 때 사용할 수 있다. 혹은 매개변수로 주어진 것의 함수를 사용할 때 사용할 수 있다.
public class FuntionMethodReference {
public static void main(String[] args) {
UnaryOperator<String> toUpperCaseLambda = input -> input.toUpperCase();
String result = toUpperCaseLambda.apply("java8");
System.out.println(result);
toUpperCaseLambda = String::toUpperCase;
result = toUpperCaseLambda.apply("java8");
System.out.println(result);
}
}
public class RefactorMethodReferenceExample {
public static Supplier<Student> studentSupplier = () -> new Student("Adam", 2, 3.6, "male", Arrays.asList("swimming, basketball"));
public static void main(String[] args) {
// Predicate<Student> p = student -> student.getGradeLevel() >= 3;
// Student에 메소드 생성 이후 참조
Predicate<Student> p = Student::greaterThanGradeLevel;
Student student = studentSupplier.get();
System.out.println(p.test(student));
}
}
생성자 참조
- 형태는 ClassName::new이다.
- Supplier를 통해 생성자를 생성하려면 아무 인자를 안 받는 기본 생성자가 있어야 한다. 왜냐하면 Supplier는 입력 인자가 없기 때문에 참조를 사용하려면 new했을 때의 인자를 못 넣기 떄문이다.
public class ConstructorReferenceExample {
public static void main(String[] args) {
Supplier<Student> studentSupplier = Student::new;
Student student = studentSupplier.get();
System.out.println(student);
}
}
- 만약 인자를 넣고 싶다면 Function과 같은 인자를 입력으로 받는 함수형 인터페이스를 이용하면 된다.
public static void main(String[] args) {
Function<String, Student> studentFunction = Student::new;
Student student = studentFunction.apply("choi");
System.out.println(student);
}