在java中实现枚举类的最佳方法

时间:2013-09-04 14:50:08

标签: java enums

我正在尝试使用所有静态枚举实现文件的最佳方法,不使用任何getter和setter,只是静态信息,我在PHP中实现这一点,如下例所示,你真的需要getter和java中的setters?

final class EnumTrade {
    const buy = 1;
    const sell = 2;
}

final class EnumGender {
    const male = 1;
    const female = 2;
}

final class EnumHttpMethod {
    const get = 1;
    const post = 2;
}

5 个答案:

答案 0 :(得分:7)

public enum EnumTrade {
  BUY, SELL
}

等等。

修改:如果数字很重要,请执行:

public enum EnumTrade {
  BUY(1), SELL(2)
}

答案 1 :(得分:2)

java enum中的

无需gettersetter这些用于普通POJObeans

示例枚举可以是:

public enum EventRecurringType {

    YEARLY("1"),
    QUARTERLY("2"),
    MONTHLY("3"),
    WEEKLY("4"),
    DAILY("5"),
    NONE("0");


    private String value;

    EventRecurringType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static EventRecurringType getEnum(String value) {
        if(value == null)
            throw new IllegalArgumentException();
        for(EventRecurringType v : values())
            if(value.equalsIgnoreCase(v.getValue())) return v;
        throw new IllegalArgumentException();
    }
}

答案 2 :(得分:0)

    public enum MyConst{ BUY(1), SELL(2), MALE(3), FEMALE(4), GET(5), POST(6);

       public final int value;

           MyConst(int value) {
               this.value = value;
           }

           public int getValue() {
               return value;
           }                                                   
    };

或者只是选择

public enum MyConst{ BUY(1), SELL(2) }; and same for MALE, FEMALE .... 

答案 3 :(得分:0)

public enum EnumTrade
{
    BUY,
    SELL,
}

如果你需要的只是枚举的序数值,你可以直接通过EnumTrade.BUY.ordinal

访问这些值。

如果要在枚举中存储其他数据,请执行以下操作(根据需要进行扩展):

public enum EnumGender
{
    MALE(1),
    FEMALE(2);

    private final int value;

    private EnumGender(String value)
    {
        this.value = value;
    }

    public int getValue()
    {
        return this.value;
    }

    //In case you need to grab an enum by the value constant
    public getEnumGender(int value)
    {
        switch(value)
        {
            case 1:
                return EnumGender.MALE;
            case 2:
            default:
                return EnumGender.FEMALE;
        }
    }
}

答案 4 :(得分:0)

为了完整性和写作时回答的问题,我改变了原来的答案提到你可以将所有的枚举存储在一个java类中。

=>最好将它们存储在自己的文件中,例如用户Tichodroma建议

然而,翻译您的exmaple代码可以用Java构建它:

public class MyEnums {

 public enum EnumTrade{
    BUY, SELL
 }

 public enum EnumGender{
    MALE, FEMALE
 }

 public enum EnumHttpMethod{
    GET, POST
 }

}

然后使用外部的不同枚举:

MyEnums.EnumTrade.BUY
相关问题