-2

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"); 
1
  • Use the built-in MyEnum.valueOf(name). Commented Aug 29, 2017 at 7:28

1 Answer 1

4

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

MyEnum foo = MyEnum.valueOf("TOTO"); MyEnum bar = MyEnum.valueOf("ZOZO"); 
Sign up to request clarification or add additional context in comments.

4 Comments

What is wrong with this answer?
Okay I misunderstood the javadoc... But in this case wouldn't it be better to use MyEnum.valueOf(MyEnum.class, "TOTO") ?
@Dynamite There is no reason for that. Trust me :)
@Dynamite that would only be useful if the first parameter were only known at runtime, e.g. you've just got a variable Class<? extends Enum<?>> someClass.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.