Java getter/setter used as Lamda’s

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);
	}
}
Ghostprogrammer
  • Ghostprogrammer
  • I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: