如何使用枚举来定义常量值组

时间:2014-07-28 04:10:47

标签: java java-ee interface enums constants

使用interface来访问项目常量 这是我的界面

public interface ConstantValues {

    interface PaymentType   {
        public static final String CREDIT_CUSTOMER = "credit";
        public static final String CASH_CUSTOMER = "cash";
    }

    interface PaymentMethode    {
        public static final String CREDIT_CARD = "creditcard";
        public static final String VISA_CARD = "visacard";
        public static final String MASTER_CARD = "mastercard";
    }

}

我从java类中访问此值,如下所示

 ConstantValues.PaymentType.CREDIT_CUSTOMER

 or

 ConstantValues.PaymentType.VISA_CARD

但我想知道如何使用枚举来做到这一点,因为使用了 定义常量的接口是不好的做法可以取悦任何人 告诉我如何使用枚举以及如何从java类访问它?

2 个答案:

答案 0 :(得分:3)

你走了:

enum PaymentType   {
    CREDIT_CUSTOMER,
    CASH_CUSTOMER;
}

enum PaymentMethod    {
    CREDIT_CARD,
    VISA_CARD,
    MASTER_CARD;
}

使用它像:

PaymentMethod meth = PaymentMethod.VISA_CARD;

答案 1 :(得分:0)

public class Enums {
    public enum Test {
        FIRST,
        SECOND,
        THIRD
    }

    public enum Test2 {
        FIRST("first"),
        SECOND("second"),
        THIRD("third");

        private final String value;

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

    public static void main(String[] args) {
        System.out.println(Enums.Test.FIRST);
        System.out.println(Enums.Test2.FIRST.value);
    }
}