简体   繁体   中英

Set Value to Enum - Java

I'm trying to set values to enum in my java application....but I can't do that.

Am I doing it wrong???

public enum RPCPacketDataType {
    PT_UNKNOWN(2),
    PT_JSON(4),
    PT_BINARY(5)
};

It's giving me this error : The constructor RPCPacket.RPCPacketDataType(int) is undefined.

public enum RPCPacketDataType
{
    PT_UNKNOWN(2),
    PT_JSON(4),
    PT_BINARY(5);

    RPCPacketDataType (int i)
    {
        this.type = i;
    }

    private int type;

    public int getNumericType()
    {
        return type;
    }
}

You can also define methods on your enum as you would in a "normal" class.

 System.out.println(RPCPacketDataType.PT_JSON.getNumericType() // => 4

You should create a Contructor which accepts an int parameter. Also add an int field which will hold the passed value.

public enum RPCPacketDataType {
    PT_UNKNOWN(2),
    PT_JSON(4),
    PT_BINARY(5);

    private int mValue;

    RPCPacketDataType(int value) {
        mValue = value;
    }
}
public enum RPCPacketDataType { 

  PT_UNKNOWN(2), 
  PT_JSON(4),
  PT_BINARY(5); 

  private int type;

  RPCPacketDataType(int type) { 
    this.type = type; 
  }

  public int getNumericType() {
    return type;
  }

  public void setNumericType(int type) {
    this.type = type;
  }

  public static void main(String[] args) {
    RPCPacketDataType.PT_UNKNOWN.setNumericType(0);
    System.out.println("Type: "+RPCPacketDataType.PT_UNKNOWN.getNumericType()); 
    // Type: 0
  }

}

As both #emboss and #Michael said correctly you can use a Contructor which accepts ant int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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