Set Value to Enum - Java
27,325
Solution 1
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
Solution 2
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;
}
}
Solution 3
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
Comments
-
Android-Droid almost 2 years
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.
-
Konstantin Burov over 12 yearsYou may also want to add a getter to have access to the value later.
-
Android-Droid over 12 yearsI have another question. How can I do something like that: RPCPacketDataType currentType; if(currentType!=PT_JSON) return;
-
Michael over 12 yearsI hope one can easily add any method to this class oneself. The question is about adding values but not retrieving them :)
-
emboss over 12 yearsI'd use
switch
for enums:switch (currentType) { case PT_JSON: ... }
-
Android-Droid over 12 yearsActually I need only to check the PT_JSON,that's why I'm using if statement.But thanks for advance!