Java中如何根据父枚举值为类属性匹配分配对应的子类型枚举值
实现方案
这里提供两种可行方案,均不需要修改现有CAR_ENUM、BIKE_ENUM、TRUCK_ENUM的代码:
方案一:泛型实现(首选,支持编译期类型校验)
第一步:修改Vehicles枚举,绑定对应子枚举类型
public enum Vehicles { CAR("This is a car", CAR_ENUM.class), BIKE("This is a bike", BIKE_ENUM.class), TRUCK("This is a truck", TRUCK_ENUM.class); private String description; private Class<? extends Enum<?>> subEnumType; private Vehicles(String description, Class<? extends Enum<?>> subEnumType) { this.description = description; this.subEnumType = subEnumType; } public String getDescription() { return description; } public Class<? extends Enum<?>> getSubEnumType() { return subEnumType; } }
第二步:定义泛型CarDealer类
public class CarDealer<E extends Enum<E>> { private Vehicles vehicle; private E subType; // 构造方法强制校验类型匹配 public CarDealer(Vehicles vehicle, E subType) { if (!vehicle.getSubEnumType().isInstance(subType)) { throw new IllegalArgumentException( String.format("类型不匹配:车辆类型%s对应的子枚举应为%s", vehicle.name(), vehicle.getSubEnumType().getSimpleName()) ); } this.vehicle = vehicle; this.subType = subType; } public Vehicles getVehicle() { return vehicle; } public E getSubType() { return subType; } public void setSubType(E subType) { if (!vehicle.getSubEnumType().isInstance(subType)) { throw new IllegalArgumentException("子枚举类型与当前车辆类型不匹配"); } this.subType = subType; } }
使用示例
// 正确用法,编译通过 CarDealer<CAR_ENUM> carDealer = new CarDealer<>(Vehicles.CAR, CAR_ENUM.SEDAN); CarDealer<BIKE_ENUM> bikeDealer = new CarDealer<>(Vehicles.BIKE, BIKE_ENUM.SPORTS); // 错误用法,编译直接报错 CarDealer<CAR_ENUM> wrongDealer = new CarDealer<>(Vehicles.CAR, BIKE_ENUM.CHOPPER);
方案二:非泛型实现(仅运行期校验,适合简单场景)
如果不需要编译期强类型校验,可以直接用Object存储子枚举值,仅做运行期校验:
public class CarDealer { private Vehicles vehicle; private Object subType; public Vehicles getVehicle() { return vehicle; } public void setVehicle(Vehicles vehicle) { this.vehicle = vehicle; // 切换车辆类型时清空原有不匹配的子枚举值,可选逻辑 this.subType = null; } public Object getSubType() { return subType; } public void setSubType(Object subType) { if (vehicle == null) { throw new IllegalStateException("请先设置车辆类型"); } if (!vehicle.getSubEnumType().isInstance(subType)) { throw new IllegalArgumentException( String.format("子枚举类型不匹配,当前车辆类型%s对应子枚举应为%s", vehicle.name(), vehicle.getSubEnumType().getSimpleName()) ); } this.subType = subType; } }
内容的提问来源于stack exchange,提问作者Gu_li4n
相关产品推荐
相关产品推荐

