Not very difficult if the return type is the same for all getters. Consider the following PoJo class:
public static class MyPoJo { final String foo, bar; public MyPoJo(String foo, String bar) { this.foo = foo; this.bar = bar; } public String getFoo() { return foo; } public String getBar() { return bar; } public int getBaz() { return 5; } }
Then we can have the following enumeration:
public static enum Getters { FOO(MyPoJo::getFoo), BAR(MyPoJo::getBar); private final Function<MyPoJo, String> fn; private Getters(Function<MyPoJo, String> fn) { this.fn = fn; } public String getValue(MyPoJo object) { return fn.apply(object); } }
And use it as follows:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue", "barValue")));
However, it would be problematic if you would like to return different types. In this case, I would suggest using a regular class with predefined instances instead of enum:
public static final class Getters<T> { public static final Getters<String> FOO = new Getters<>(MyPoJo::getFoo); public static final Getters<String> BAR = new Getters<>(MyPoJo::getBar); public static final Getters<Integer> BAZ = new Getters<>(MyPoJo::getBaz); private final Function<MyPoJo, T> fn; private Getters(Function<MyPoJo, T> fn) { this.fn = fn; } public T getValue(MyPoJo object) { return fn.apply(object); } }
Usage is the same:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue", "barValue"))); // fooValue System.out.println(Getters.BAZ.getValue(new MyPoJo("fooValue", "barValue"))); // 5
source share