我有一个包含多个属性的类,其中一个是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
}
}
我将该类放入列表中,并填充一些值:
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一样使用该类,并使用其getter和setter:
System.out.println(car.get(0));
但是,以我为例,我只会得到:
Car{manufacturer=Mazda, power=95}
因此,缺少
color
属性。如何将
enum
类型用作类的常规属性? 最佳答案
您可以像使用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);