简体   繁体   English

将值设置为枚举 - Java

[英]Set Value to Enum - Java

I'm trying to set values to enum in my java application....but I can't do that. 我正在尝试在我的java应用程序中将值设置为枚举....但我不能这样做。

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. 它给了我这个错误:构造函数RPCPacket.RPCPacketDataType(int)是未定义的。

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. 您应该创建一个接受int参数的Contructor。 Also add an int field which will hold the passed value. 还要添加一个int字段,它将保存传递的值。

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 正如#emboss和#Michael都正确地说你可以使用接受ant int Contructor

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

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