Is there anyway to check if an enum exists by comparing it to a given string? I can’t seem to find any such function. I could just try to use the valueOf method and catch an exception but I’v been taught that catching runtime exceptions is not good practice. Anybody have any ideas?
Is there anyway to check if an enum exists by comparing it to a
Share
I don’t think there’s a built-in way to do it without catching exceptions. You could instead use something like this:
Edit: As Jon Skeet notes,
values()works by cloning a private backing array every time it is called. If performance is critical, you may want to callvalues()only once, cache the array, and iterate through that.Also, if your enum has a huge number of values, Jon Skeet’s map alternative is likely to perform better than any array iteration.