0

I have an enum a I would like set a value (exampleValue) based on another value (size). Of course this does not work, because I can't use this in a static context.

private enum FIELDS {
    FIELD_2("Field 1", 1, 8, StringUtils.leftPad("A", this.getSize(), "X")),
    FIELD_3("Field 2", 2, 7, StringUtils.leftPad("A", this.getSize(), "X")) ,
    FIELD_4("Field 3", 3, 9, StringUtils.leftPad("A", this.getSize(), "X"));
    
    private final String description;
    private final int number;
    private final int size;
    private final String exampleValue;
    
    FIELDS(String description, int number, int size, String exampleValue) {
      this.description = description;
      this.number = number;
      this.size = size;
      this.exampleValue = exampleValue;
    }

    public String getDescription() {
      return description;
    }
    
    public int getNumber() {
      return number;
    }

    public int getSize() {
      return size;
    }

    public String getExampleValue() {
      return exampleValue;
    }
}

But is there a clean Java-esque way to do it?

AndreasInfo
  • 1,062
  • 11
  • 26
  • 2
    Don't make it a constructor parameter. Set it within the constructor, because at that point you know what `size` is. `this.exampleValue = StringUtils.leftPad("A", size, "X");` if you need different "A" or "X", you can pass them as constructor parameters – XtremeBaumer Oct 17 '22 at 06:33
  • What do you mean with "pass them as constructor parameters"? Make more "columns" with e. g. exampleChar and paddingChar? – AndreasInfo Oct 17 '22 at 06:44
  • Yes, if they are not static, you make a constructor like `FIELDS(String description, int number, int size, String exampleChar, String paddingChar)` – XtremeBaumer Oct 17 '22 at 06:54

1 Answers1

0

You cannot invoke a getter for size before the instance of FIELDS enum is constructed.

However, it is possible to implement an overloaded constructor to populate exampleValue depending on the size parameter to get rid of multiple calls to StringUtils.leftPad:

public enum FIELDS {
// enum values and fields

    FIELDS(String description, int number, int size) {
      this(description, number, size, StringUtils.leftPad("A", size, "X"));
    }

    FIELDS(String description, int number, int size, String exampleValue) {
      this.description = description;
      this.number = number;
      this.size = size;
      this.exampleValue = exampleValue;
    }
// ... getters
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42