Set Value to Enum - Java
I'm trying to set values to enum in my java application....but I can't do that.
开发者_如何学CAm 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
精彩评论