简体   繁体   English

获取枚举字段的值

[英]Getting the value of an enum field

I have an enumeration of byte values: 我有一个字节值的枚举:

        public class ByteMessage {

            public enum Messages {
                ACK(0x01), CHAT(0x02), TURN(0x02), WAITING(0x03), REMATCH(0x04), DOUBLE(0x05), LOADREQUEST(0x06), LOADCOMPLETE(0x07),
                ROLL(0x08), DBLACCEPTORDECLINE(0x09), DBLRECV(0x0A), ALERTPEERNOPOSSIBLES(0x0B), UPDATEDIES(0x0C),
                SETTURN(0x0D), SETFIRSTROLL(0x0E), CALCPOSSIBLEINDEXES(0x0F), LOADGAMEREQUEST(0x10), LOADGAMECOMPLETE(0x11), PUSHSTATUSTEXT(0x12),
                ISDOUBLESOWNER(0x13);

                private final byte id;

                Messages(int id) {
                    this.id = (byte) id;
                }

                public byte getId() {
                    return this.id;
                }
            }

In another class I have this function: 在另一个类中,我具有以下功能:

            private void SendACK()
            {
                byte[] message = new byte[10];

                //Neither one of these will compile I have to return back the byte value of ACK
                //Byte a = new Byte(ByteMessage.M.ACK);
                //message[0] = ByteMessage.M.ACK;

Is there a way to get the byte value back out of the enum? 有没有办法从枚举中取回字节值?

Thank you! 谢谢!

You should use the getId method of your Message enum : 您应该使用Message枚举的getId方法:

message[0] = ByteMessage.M.ACK.getId();

Each constant in an enum is an instance of the enum . 在每一个常数enum是实例enum Just like classes, an instance of an enum can have data. 就像类一样, enum的实例可以具有数据。 In your specific case, each enum constant has an id which is initialized when the enum constant is created and can be accessed through the getId member method. 在您的特定情况下,每个enum常量都有一个id ,该id在创建enum常量时初始化,并且可以通过getId成员方法进行访问。

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

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