Getter enum

Is an enumeration capable of storing getter method references using Supplier ?

For use:

 String value = myEnum.getValue(object) 

I cannot figure out how to write it without compiling errors.

+6
source share
2 answers

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"))); // fooValue 

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 
+5
source

If I get you right, you want to do something like this:

 import java.util.function.DoubleSupplier; public class Test { enum MathConstants { PI(Test::getPi), E(Test::getE); private final DoubleSupplier supply; private MathConstants(DoubleSupplier supply) { this.supply = supply; } public double getValue() { return supply.getAsDouble(); } } public static void main(String... args) { System.out.println(MathConstants.PI.getValue()); } public static double getPi() { return Math.PI; } public static double getE() { return Math.E; } } 
+6
source

All Articles