51

I am receiving return value in the form of long or int from Native code in Android, which I want to convert or match with enum, for processing purpose. Is it possible ? How?

Jim G.
  • 14,600
  • 19
  • 100
  • 158
Sachchidanand
  • 1,271
  • 2
  • 19
  • 35

2 Answers2

66

If you have full control of values and enums, and they're sequential, you can use the enum ordinal value:

enum Heyo
{
  FirstVal, SecondVal
}

...later

int systemVal = [whatever];
Heyo enumVal = Heyo.values()[systemVal];

int againSystemVal = enumVal.ordinal();
Kevin Galligan
  • 15,346
  • 5
  • 40
  • 58
62

You can set up your enum so it has the long or int built into it.

e.g: Create this file ePasswordType.java

public enum ePasswordType {

    TEXT(0),
    NUMBER(1);

    private int _value;

    ePasswordType(int Value) {
        this._value = Value;
    }

    public int getValue() {
            return _value;
    }

    public static ePasswordType fromInt(int i) {
        for (ePasswordType b : ePasswordType .values()) {
            if (b.getValue() == i) { return b; }
        }
        return null;
    }
}

You can then access the assigned values like this:

ePasswordType var = ePasswordType.NUMBER;

int ValueOfEnum = var.getValue();

To get the enum when you only know the int, use this:

ePasswordType t = ePasswordType.fromInt(0);

Enums in java are very powerful as each value can be its own class.

Kuffs
  • 35,313
  • 10
  • 77
  • 92
  • 6
    This is a much better approach than using ordinal(). To learn why, read Effective Java – David Snabel-Caunt Nov 07 '11 at 12:36
  • @Kuffs: Is there also a proper way to **set** the enum by using the integer value? – Levite Dec 15 '14 at 14:42
  • @Levit The value is set at design time not run time. If you mean retrieve the enum value when you only know the int, see my edited answer. – Kuffs Dec 16 '14 at 08:48
  • 2
    @DavidSnabel-Caunt Could I impose on you to save me the cost and trouble of acquiring Effective Java for the sole purpose of finding out why ordinal() is bad, and provide an explanation. – Robin Davies Jun 02 '18 at 15:08
  • 1
    @robin-davies check out this question. https://stackoverflow.com/questions/44654291/is-it-good-practice-to-use-ordinal-of-enum – Kuffs Jun 03 '18 at 15:58