Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Enum by value using SnakeYAML

As specified in the docs and seen from the source code, SnakeYAML works with enums by their names. What I'd like to have is to parse values by enum value, e.g.:

Enum:

public enum Strategy {
    ALWAYS_RUN("always-run"),
    ALWAYS_SKIP("always-skip"),
    DEPENDS("depends");
    ...
}

YAML:

branches:
  trunk: always-skip
  bugfix: depends
  default: always-run

The reason is our code style forces us to use uppercase for enum constants, while I'd like to keep data in the yaml file lowercase.

like image 470
Actine Avatar asked Oct 27 '25 20:10

Actine


1 Answers

As far as I am aware, this is not possible. Enum constants are private, and are therefore not accessible by other classes, so the YAML parser would not be able to construct the objects.

Although not perfect, you could use aliases to create a nickname for the enums.

like image 153
Ben Green Avatar answered Nov 01 '25 06:11

Ben Green