Once again I’m looking into ways to make coding so much easier. I needed to be able to pass in a Class::get and a Class:set as a Lamda in order to be able to reuse code across types. It’s a rather simple process. However I have not found it really documented elsewhere. Therefore I hope this article helps someone on this issue.
The getter is simple: Function<? super T,? extends R> getter
Use this Functional Interface to be able to pass in your getter. Class::get
The setter is simple: BiConsumer<T, R> setter
Use this Functional Interface to be able to pass in your setting. Class:set
Here is a simple Java Bean we will use:
public class Person {
private String name;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
Here is our Actor class that will operate on the Java Beam:
public class Actor {
public <T> void printField(T obj, Function<? super T,? extends R> getter) {
System.out.println(getter.apply(obj).toString());
}
public <T,R> void setField(T obj, R value, BiConsumer<T, R> setter) {
setter.accept(obj, value);
}
public static void main(String[] args) {
Person person = new Person();
Actor actor = new Actor();
actor.setField(person, "Bob", Person::setName);
actor.printField(person, Person::getName);
}
}
Discover more from GhostProgrammer - Jeff Miller
Subscribe to get the latest posts sent to your email.