在 Class 中将枚举视为常规 属性

Treating Enum as regular property in Class

我有一个 class 由几个属性组成,其中之一是 enum:

public class Car {

    private String manufacturer;
    private int power;

    public enum Color {
        RED("red"),
        BLUE("blue"),
        GREEN("green");

        private final String value;

        Color(final String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public int getPower() {
        return power;
    }

    public void setPower(int power) {
        this.power = power;
    }

    public Car(String manufacturer, int power, Color color) {
        this.manufacturer = manufacturer;
        this.power = power;
//        Color(color); // Calling constructor, but --> ERROR: cannot find symbol
    }

    @Override
    public String toString() {
        return "Car{" + "manufacturer=" + manufacturer + ", power=" + power + '}'; // TODO add color
    }

}

我将 class 放入列表中并用一些值填充它:

List<Car>  car = Arrays.asList(
          new Car("Mazda", 95, Car.Color.BLUE),
          new Car("Toyota", 110, Car.Color.RED),
          new Car("Honda", 85, Car.Color.GREEN)
  );

我想要的是像常规 DTO 一样使用它 class,使用它的 getter 和 setter:

System.out.println(car.get(0));

但在我的案例中,我只得到:

Car{manufacturer=Mazda, power=95}

因此缺少 color 属性。

如何将 enum 类型用作 class 的常规 属性?

您可以像 java 中的任何其他类型一样使用枚举类型。试试看:

private String manufacturer;
private int power;
private Color color;  // here is the property of enum type

....

public Car(String manufacturer, int power, Color color) {
    this.manufacturer = manufacturer;
    this.power = power;
    this.color = color;
}

Car newCar = new Car("manufacturer", 150, Color.RED);

我个人会将枚举放在自己的文件中(只是为了便于阅读),并在您的 class 汽车中将枚举作为成员变量。

然后在你的枚举文件中放一个像这样的 toString 函数

   public String toString()
   {
        String returnValue = "";

        switch (this)
        {
           case RED:
            returnValue = "Red";
            break;
           case BLUE:
            returnValue = "Blue";
            break;
        }

        return returnValue;
    }

然后在汽车的 toString 中执行:

return "Car{" + "manufacturer=" + manufacturer + ", power=" + power + " Colour = " + colour.toString() + "}";

其中 color 是此 class 中枚举的成员变量。