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)