简体   繁体   English

在Java bean中声明枚举变量

[英]Declare enum variable in Java bean

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. 我需要将一个枚举变量声明为一个类成员,并且需要像java bean一样为它定义一个setter和getter。 something like this - 像这样的东西 -

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. 现在,我想将color属性设置为红色,绿色或任何其他类,并希望相应地做出决定。

The enum will have to be made public to be seen by the outside world: enum必须公开以供外界看到:

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相同的包中使用Vehicle.Color,则可以从enum声明中删除public

If you want to work with your color enum, you have to share its declaration more widely than you're doing. 如果你想使用你的color枚举,你必须比你正在做的更广泛地分享它的声明。 The simplest might be to put public in front of enum color in Vehicle. 最简单的可能是将public放在车辆中的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. 我建议你将枚举的名称从color改为Color ,因为它基本上都是一个类。 Then you can declare a field: private Color color among with your other fields. 然后你可以声明一个字段: 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. 要使用枚举,尤其是来自另一个类的常量,您需要知道枚举嵌套在Vehicle中。 You need to qualify all names, so: 您需要限定所有名称,因此:

Vehicle.Color myColor = Vehicle.Color.RED;

Bakkal has kindly written code to demonstrate much of what I was talking about. Bakkal亲切地编写了代码来展示我所谈论的内容。 See his answer for details! 详情请见他的回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM