string - Check if enum exists in Java -
Is it anyway to check whether a value exists by comparing a given string? I can not find any such work that I can try to use the valueOf
method and catch the exception but I'v was taught that catching the runtime exception is not a good practice. Have any ideas?
I do not think there is an underlying way without catching it is no exception. You can use something in return:
public stable MyEnum asMyEnum (string str) {for (MyEnum me: MyEnum.values ()) {if (me.name () EqualsIgnoreCase (str)) me back; } Return tap; } Edit: As John Skeet notes, value ()
each time it is called when a private backing array Cloning works by. If performance is important, you can call value ()
only once, cache arrays, and iterate through it. In addition, if your enum has too many values, the map sketch map option is likely to perform better than any other move.
Comments
Post a Comment