简体   繁体   中英

how to use the toString() method for multiple enum members in same class in Java

I am trying to add more user friendly descriptions for multiple enum members in the same class. Right now I just have each enum returned in lowercase:

public enum Part {
    ROTOR, DOUBLE_SWITCH, 100_BULB, 75_BULB, 
    SMALL_GAUGE, LARGE_GAUGE, DRIVER;

    private final String description;

    Part() {
      description = toString().toLowerCase();
    }

    Part(String description) {
      this.description = description;
    }

    public String getDescription() {
      return description;
    }
}

Is there a way to give each enum value a more user-friendly name which I can display via the toString() for each Part member? For example when I interate over the Parts:

for (Part part : Part.values()) {
System.out.println(part.toString());
}

rather than getting the literal list:

ROTOR
DOUBLE_SWITCH
100_BULB
75_BULB 
SMALL_GAUGE
LARGE_GAUGE
DRIVER

I am hoping to give meaningful descriptions to each item so I can output something like:

Standard Rotor
Double Switch
100 W bulb
75 W bulb 
Small Gauge
Large Gauge
Torque Driver

So I was wondering if there is a way to give those meaningful descriptions for each enum member in my Part enum class.

Many thanks

Enums are really classes in disguise, forced to be a single instance. You can do something like this below to give each a name. You can give it any number of proprties you like in the constructor. It doesn't affect how you reference it. In the example below, ROTOR will have a string representation of "This is a rotor".

public enum Part {
  ROTOR("This is a rotor");

  private final String name;

  Part(final String name) {
      this.name = name;
  } 

  @Override
  public String toString() {
      return name;
  }
}

Yes, you already have a constructor that takes a description. Why not use that?

public enum Part {
    ROTOR<b>("Rotor")</b>, DOUBLE_SWITCH<b>("Double Switch")</b>, 100_BULB, 75_BULB, 
    SMALL_GAUGE, LARGE_GAUGE, DRIVER;

    private final String description;

    Part() {
      description = toString().toLowerCase();
    }

    Part(String description) {
      this.description = description;
    }

    public String getDescription() {
      return description;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM