Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with a getter

Tags:

java

enums

java-8

Is an enum able to store references to a getter method, using a Supplier?

To be use like that :

String value = myEnum.getValue(object)

I can't figure how to write it without compiling errors.

like image 866
Barium Scoorge Avatar asked Sep 15 '15 15:09

Barium Scoorge


1 Answers

If I get you right then 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;
  }
}
like image 163
Flown Avatar answered Sep 23 '22 10:09

Flown