Friday 4 November 2016

Getting java enum by name





Is it possible to get an enum by searching on its name instead of value ? For example :



public enum MyEnum {
TOTO("some value", 1);
ZOZO("some other value", 2);
}


And what I want to do is a getter like :




public static MyEnum getByName(String str) {
[...]
}


So I can do :



MyEnum foo = MyEnum.getByName("TOTO");
MyEnum bar = MyEnum.getByName("ZOZO");


Answer



Each Java enum has method valueOf(String name) which returns enum by name.



MyEnum foo = MyEnum.valueOf("TOTO");
MyEnum bar = MyEnum.valueOf("ZOZO");

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...