Java – enumeration with getter
•
Java
Can enumerations use vendors to store references to getter methods?
Use this:
String value = myEnum.getValue(object)
I can't imagine how to write it without compiling errors
Solution
If all getters have the same return type, it is not very difficult Consider the following POJO classes:
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 may have such an 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 like this:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue","barValue"))); // fooValue
However, if you want to return different types, there will be a problem In this case, I recommend using normal classes with predefined instances instead of enumerations:
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); } }
The 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码