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?
Asked
Active
Viewed 4.3k times
2 Answers
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
-
9Use of the ordinal to get a "value" for an enum is not recommended. Instead, use an instance field instead. See Item 31 in the 2nd edition of Josh Bloch's Effective Java. – Vito Andolini Nov 04 '16 at 20:24
-
1Why is not recommended? – Robin Davies Jun 02 '18 at 15:05
-
2@RobinDavies If someone (ie. from your team) will add value in the middle or beginning it will mess up whole code using .ordinal() – callmebob Nov 06 '18 at 16:22
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
-
6This 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