gpt4 book ai didi

java - 参数化 Java 枚举

转载 作者:行者123 更新时间:2023-12-01 11:15:08 25 4
gpt4 key购买 nike

如何在 Java 中参数化一个或多个 enum 值?

我有 3 个非常相似的 enum:ActiveStateGreenRed,ActiveStateGreenOrangeActiveStateGreenYellow

如何制作“通用”enum(我们称之为ActiveState)和“继承”enum:

ActiveStateGreenRed = ActiveState(STATE_COLOR.RED)

ActiveStateGreenOrange = ActiveState(STATE_COLOR.ORANGE)

public enum ActiveStateGreenRed {
INACTIVE(false, STATE_COLOR.RED), //the only difference between enums
ACTIVE(true, STATE_COLOR.GREEN);

private final Boolean value;
private final STATE_COLOR color;

private ActiveStateGreenRed(Boolean value, STATE_COLOR color) {
this.value = value;
this.color = color;
}

public Boolean toValue() {
return value;
}

public STATE_COLOR toColor() {
return color;
}
}

最佳答案

enum 无法继承。你可以做类似的事情:

public enum ActiveState {
INACTIVE_RED(false, STATE_COLOR.RED), //the only difference between enums
ACTIVE_RED(true, STATE_COLOR.RED),

INACTIVE_GREEN(false, STATE_COLOR.GREEN),
ACTIVE_GREEN(true, STATE_COLOR.GREEN);

...
}

或者,采用“经典”预枚举方式:

public final class ActiveState {

public final static ActiveState ACTIVE_RED = new ActiveState( true, STATE_COLOR.RED );

public final static ActiveState ACTIVE_GREEN = new ActiveState( true, STATE_COLOR.GREEN );

...

private final Boolean value;
private final STATE_COLOR color;

private ActiveState(Boolean value, STATE_COLOR color) {
this.value = value;
this.color = color;
}

}

一般来说,具有(包)私有(private)构造函数(仅提供预定义的常量实例)的类可以很像枚举。并且您可以使用这些类拥有继承层次结构。

关于java - 参数化 Java 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com