恩格用吸气剂

时间:2015-09-15 15:08:02

标签: java enums java-8

枚举是否能够使用Supplier

存储对getter方法的引用

这样使用:

String value = myEnum.getValue(object)

我无法在不编译错误的情况下编写文章。

2 个答案:

答案 0 :(得分:6)

如果我说得对,那么你想做这样的事情:

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;
  }
}

答案 1 :(得分:5)

如果所有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