如何将getter作为lambda函数传递?

mem*_*und 10 java lambda java-8

我想将bean的getter作为函数传递.调用该函数时,应调用getter.例:

public class MyConverter {
    public MyConverter(Function f) {
          this.f = f;
    }

    public void process(DTO dto) {
         // I just want to call the function with the dto, and the DTO::getList should be called
         List<?> list = f.call(dto);
    }
}

public class DTO {
    private List<String> list;
    public List<String> getList() { return list; }
}
Run Code Online (Sandbox Code Playgroud)

这有可能与Java 8?

Mic*_*ael 13

如果构造函数MyConverter必须带一个函数,并且process必须带一个对象,这可能是最好的方法:

class MyConverter<T> {
    //               V takes a thing (in our case a DTO)
    //                       V returns a list of Strings
    private Function<T, List<String>> f;

    public MyConverter(Function<T, List<String>> f) {
          this.f = f;
    }

    public void process(T processable) {
         List<String> list = f.apply(processable);
    }
}

MyConverter<DTO> converter = new MyConverter<>(DTO::getList);

DTO dto = new DTO();
converter.process(dto);
Run Code Online (Sandbox Code Playgroud)

  • 正如OP在前面的评论中所说的那样,"我的目标是转换器必须不知道DTO*的实现"这只是一个建议,这使得将"DTO"转换为类型变量是一种自然的解耦代码的方式. (3认同)
  • 因此``DTO`可以是`MyConverter`的类型变量. (2认同)