[英]How do I get “Enum.CONSTANT” to return some type (e.g. Color)?
I want the field constants of my enum to return instances of the Color
class instead of some constant values, is this possible in Java? 我希望枚举的字段常量返回
Color
类的实例而不是某些常量值,这在Java中可能吗? I would like to avoid having to retrieve them through an accessor method. 我想避免必须通过访问器方法检索它们。 For example, this is the way I want to be able to use my enum:
例如,这就是我希望能够使用枚举的方式:
Color color;
color = ExtendedColor.RED;
color = ExtendedColor.FOO;
color = ExtendedColor.BAZ;
import java.awt.*;
/**
* Static utility enum for providing a much greater variety of Colors to choose from, some of which are not
* included as constants in the Color class
*/
public enum ExtendedColor {
RED(Color.RED),
ORANGE(Color.ORANGE),
YELLOW(Color.YELLOW),
FOO(10, 20, 30),
BAR(90, 90, 90),
BAZ(30, 30, 30);
private Color color;
private ExtendedColor(Color color) {
this.color = color;
}
private ExtendedColor(int r, int g, int b) {
this.color = new Color(r, g, b);
}
}
You can create a class with public static fields instead and access the fields directly ExtendedColor.COLOR1
. 您可以改用具有公共静态字段的类,并直接访问
ExtendedColor.COLOR1
的字段。
import java.awt.*;
public class ExtendedColor {
public static final Color COLOR1 = ...;
public static final Color COLOR2 = ...;
...
}
One approach is given in the first answer. 第一个答案给出了一种方法。 Another approach is to define a
colorValue
method in the ExtendedColor
enum which returns the actual Color. 另一种方法是在
ExtendedColor
枚举中定义colorValue
方法,该方法返回实际的Color。
public enum ExtendedColor {
...
public Color colorValue() {
return color;
}
}
And then you will have 然后你将有
Color color;
color = ExtendedColor.RED.colorValue();
color = ExtendedColor.FOO.colorValue();
color = ExtendedColor.BAZ.colorValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.