6
是一個枚舉能夠存儲對getter方法的引用,使用Supplier
?Enum with a getter
要這樣使用:
String value = myEnum.getValue(object)
我想不出怎麼寫不編譯錯誤。
是一個枚舉能夠存儲對getter方法的引用,使用Supplier
?Enum with a getter
要這樣使用:
String value = myEnum.getValue(object)
我想不出怎麼寫不編譯錯誤。
這不是很困難的,如果所有的getter的返回類型是一樣的。請看下面的POJO類:
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;
}
}
那麼我們可能有這樣的枚舉:
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);
}
}
而且使用這樣的:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue", "barValue"))); // fooValue
但是如果你想要回這將是有問題的不同種類。在這種情況下,我建議使用普通類與預定義的實例,而不是枚舉:
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);
}
}
用法是相同的:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue", "barValue"))); // fooValue
System.out.println(Getters.BAZ.getValue(new MyPoJo("fooValue", "barValue"))); // 5
如果我得到你的權利,那麼你想要做這樣的事情:
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;
}
}
爲什麼不'的valueOf()'? 'String result = myEnum.valueOf(object); ' –
我想存儲對另一個對象的吸氣劑的引用 –
當然,你可以。 'enum'值是Java對象,因此它們可以容納普通對象所能容納的任何東西。但是如果你正在討論綁定到實例的getter,它聽起來不像推薦的代碼風格,並且可能是XY問題。 – Holger