ytg
ytg

Reputation: 1857

Getting Enum values differently

I recently encountered a code change (and I can't ask the guy who did it). He changed the following:

//String bar;
MyEnum foo = MyEnum.valueOf(bar);

To:

//String bar;
MyEnum foo = MyEnum.valueOf(MyEnum.class, bar);

What difference does it make (given that valueOf() has not been overridden for MyEnum)?

Upvotes: 2

Views: 50

Answers (1)

GhostCat
GhostCat

Reputation: 140525

The second approach is definitely "bad style" - as it calls a static method of Enum.class on some other class. Meaning:

MyEnum foo = Enum.valueOf(MyEnum.class, bar);

would at least be more consistent. And quoting from the javadoc for valueOf():

Note that for a particular enum type T, the implicitly declared public static T valueOf(String) method on that enum may be used instead of this method to map from a name to the corresponding enum constant. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

So, long story short; there is no valid reason to replace ConcreteEnum.valueOf(String) with ConcreteEnum.valueOf(Class, String). To the contrary.

Upvotes: 1

Related Questions