I want to pass the getter of a bean as a function. When the function is called the getter should be invoked. Example:
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; }
}
Is that possible with java 8?
If the constructor of MyConverter
must take a function, and process
must take an object, this is probably the best way:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With