使用 toString() 后如何从枚举中获取字符串

How can i can get Strings from Enum after using toString()

我正在创建一个列表,用户可以从中 select 使用 Vaadin8。我想从枚举中获取值,但带有空格的字符串值不是元素名称。

public enum CustomerStatus {
    
    ImportedLead {
        public String toString() {
            return "Imported Lead";
        }
    }, 
     NotContacted{
        public String toString() {
            return "Not Contacted";
        }
    }, 
     Contacted{
        public String toString() {
            return "Contacted";
        }
    }, 
     Customer{
        public String toString() {
            return "Customer";
        }
    }, 
     ClosedLost{
        public String toString() {
            return "Closed Lost";
        }
    }
}

这是从 Enum 元素创建到 select 的列表:

private NativeSelect <CustomerStatus> status = new NativeSelect<>("Status");

这里有 3 行我试过但没有用:

status.setItems(CustomerStatus.values().toString());

//
status.setItems(CustomerStatus.valueOf(CustomerStatus.values())); 
//
status.setItems(CustomerStatus.ClosedLost.toString(), CustomerStatus.Contacted.toString() , CustomerStatus.Customer, CustomerStatus.NotContacted, CustomerStatus.ImportedLead);
//

你可以给你的 enum 以下内容:

            @Override
            public String toString() {
                String result = super.toString();
                return result.replaceAll("([A-Z][a-z]+)([A-Z][a-z]+)", " ");
            }

你可以添加一个value 属性:

  public enum CustomerStatus {

  ImportedLead("Imported Lead"),
  NotContacted("Not Contacted"),
  Contacted("Contacted"),
  Customer("Customer"),
  ClosedLost("Closed Lost");

  private final String value;

  CustomerStatus(String value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return this.value;
  }

  public static CustomerStatus fromValue(String value) {
    CustomerStatus result = null;
    switch(value) {
      case "Imported Lead":
      result = CustomerStatus.ImportedLead;
      break;
      case "Not Contacted":
      result = CustomerStatus.NotContacted;
      break;
      case "Contacted":
      result = CustomerStatus.Contacted;
      break;
      case "Customer":
      result = CustomerStatus.Customer;
      break;
      case "Closed Lost":
      result = CustomerStatus.ClosedLost;
      break;
    }
    if (result == null) {
      throw new IllegalArgumentException("Provided value is not valid!");
    }
    return result;
  }
}

用法:

status.setItems(Arrays.asList(CustomerStatus.values()));