Skip to content
Advertisement

set class fields based on enum value

enum Temp {
  VALUE1(Tempclass::getField1)
  VLAUE2(Tempclass::getField2)
  private final Function<Tempclass, String> type;
}

class Tempclass {
  String field1;
  String field2;
}

Using the above code I can get the value of Tempclass fields based on enum values. Now how to set the fields of Tempclass based on enum value ex: if enum VALUE2 is selected, then i need to set the Tempclass field2 to the input value.

Advertisement

Answer

Use a BiConsumer<Tempclass, String> taking an instance of TempClass and a String and set the appropriate field in the class.

VALUE1(Tempclass::getField1, Tempclass::setField1),
VALUE2(Tempclass::getField2, Tempclass::setField2);

private final BiConsumer<Tempclass, String> setter;

Get the setter from the enum and pass the values to the accept method of the BiConsumer.

enumInstance.getSetter().accept(tempClassInstance, "some-value");
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement