在 Java bean 中声明枚举变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3267520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare enum variable in Java bean
提问by Saurabh
I need to declare an enum variable as a class member and need to define a setter and getter for that like a java bean. something like this -
我需要将一个枚举变量声明为类成员,并需要为它定义一个 setter 和 getter,就像一个 java bean。像这样的——
public class Vehicle {
private String id;
private String name;
enum color {
RED, GREEN, ANY;
}
// setter and getters
}
Now, I want to set color property as red, green or any from some other class and want to make decisions accordingly.
现在,我想将颜色属性设置为红色、绿色或其他类中的任何属性,并希望做出相应的决定。
采纳答案by bakkal
The enum will have to be made public to be seen by the outside world:
枚举必须公开才能被外界看到:
public class Vehicle {
private String id;
private String name;
public enum Color {
RED, GREEN, ANY;
};
private Color color;
public Color getColor(){
return color;
}
public void setColor(Color color){
this.color = color;
}
}
Then from outside the package you can do:
然后从包外,您可以执行以下操作:
vehicle.setColor(Vehicle.Color.GREEN);
if you only need to use Vehicle.Color inside the same package as Vehicle
you may remove the public
from the enum
declaration.
如果您只需要在同一个包中使用 Vehicle.Color ,Vehicle
您可以public
从enum
声明中删除。
回答by Carl Smotricz
If you want to work with your color
enum, you have to share its declaration more widely than you're doing. The simplest might be to put public
in front of enum color
in Vehicle.
如果你想使用你的color
枚举,你必须比你正在做的更广泛地共享它的声明。最简单的可能是放在Vehiclepublic
前面enum color
。
Next, you need to declare a field of the enum's type. I suggest you change the name of the enum from color
to Color
, because it's basically a class anyway. Then you can declare a field: private Color color
among with your other fields.
接下来,您需要声明一个枚举类型的字段。我建议您将枚举的名称从 更改color
为Color
,因为无论如何它基本上都是一个类。然后你可以声明一个字段:private Color color
在你的其他字段中。
To use the enum and especially its constants from another class, you need to be aware that the enum is nested in Vehicle. You need to qualify all names, so:
要使用枚举,尤其是来自另一个类的常量,您需要注意枚举嵌套在 Vehicle 中。您需要限定所有名称,因此:
Vehicle.Color myColor = Vehicle.Color.RED;
Bakkal has kindly written code to demonstrate much of what I was talking about. See his answer for details!
Bakkal 编写了代码来演示我所说的大部分内容。详情请看他的回答!