2016-10-27 8 views
0

메서드에 대한 참조를 매개 변수로 전달할 수 있습니까? 예를 들어함수 참조를 매개 변수로 전달

:

public static void main(String[] args) { 
    String data = "name: John, random text, address: leetStreet"; 
    Person person; 

    //if regex matches, use method reference, to send the result. 
    applyDataToPerson(data, "name: (\\w+)", person, Person::setName); 
    applyDataToPerson(data, "address: (\\w+)", person, Person::setAddress); 
} 

private static void applyDataToPerson(String data, String regex, Person person, 
Function<Person> f) { 
    Matcher match = Pattern.compile(regex).matcher(data); 
    if (match.matches()) person.f(match.group(1)); 
} 

class Person { 
    private String name; 
    private String address; 

    public void setName(String name) { 
     this.name = name; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 
} 

그렇지 않다면, 방법에 대한 참조를 제공하는 대안이 될 것입니다 무슨? 스위치 케이스 구조?

+2

을 기존 메소드 (다른 것들 중에서)에 [메소드 참조] (https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)를 전달할 수 있습니다. – Tibrogargan

+0

@Tibrogargan 메소드 서명은 어떻게 생겼습니까? 'Comparator '는 나에게 의미가 없습니다. – JasperJ

+1

'Function '은 무엇을 나타낼 것입니까? 우리가 ['java.util.function.Function'] (https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html)에 대해 말하면, 2 1. generic이 아닌 코드는 ... ('person.f (...)'는 말할 것도없고) ...로 시작하도록 컴파일 할 수 없습니다. _alternatives_를 요청하기 전에 작업 코드가 있는지 확인하십시오 ... – Tunaki

답변

5

나는 당신이 BiConsumer 찾고있는 생각 :

private static void applyDataToPerson(String data, String regex, Person person, BiConsumer<Person, String> action) { 
    Matcher match = Pattern.compile(regex).matcher(data); 
    if (match.matches()) action.accept(person, match.group(1)); 
} 

다른 방법으로,이 방법 서명을 단축하고 person 참조 캡처 단일 인수 Consumer 사용할 수 있습니다 : 자바 8에서

public static void main(String[] args) { 
    String data = "name: John, random text, address: leetStreet"; 
    Person person; 

    //if regex matches, use method reference, to send the result. 
    applyData(data, "name: (\\w+)", person::setName); 
    applyData(data, "address: (\\w+)", person::setAddress); 
} 

private static void applyData(String data, String regex, Consumer<String> action) { 
    Matcher match = Pattern.compile(regex).matcher(data); 
    if (match.matches()) action.accept(match.group(1)); 
} 
+0

그리고 기본 메소드에서 biconsumer 함수를 작성하십시오 :'applyDataToPerson (data, "name : (\\ w +)", person, (Person p, String s) > p.setName (s)); applyDataToPerson (데이터, "주소 : (\\ w +)", 사람, (사람 p, 문자열 s) -> p.setAddress (s)), ' – gaston

+2

@gaston 아니요, 주요 방법은 OP가 가진 것과 정확히 같습니다. – shmosel

+2

개인적으로 나는 두 번째 옵션을 좋아합니다. –

관련 문제