在Java bean中声明枚举变量 [英] Declare enum variable in Java bean

查看:302
本文介绍了在Java bean中声明枚举变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个枚举变量声明为一个类成员,并且需要像java bean一样为它定义一个setter和getter。这样的事情 -

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 -

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.

推荐答案

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;
     }   

    } 

然后从外面你可以做的包:

vehicle.setColor(Vehicle.Color.GREEN);

如果你只需要在与车辆相同的包装内使用Vehicle.Color 您可以从 enum 声明中删除 public

if you only need to use Vehicle.Color inside the same package as Vehicle you may remove the public from the enum declaration.

这篇关于在Java bean中声明枚举变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆