user1451415
user1451415

Reputation: 107

Can one convert a String to an enum value?

I have got code like this:

BufferedReader in = new BufferedReader(new FileReader("C:\file.txt"));
String text = in.readLine();//lets say text is now "asd"

Now after that i have got a method:

private static void doSomething(Enum word){
    ...
}

Is it possible to somehow convert this text into an Enum?

Upvotes: 1

Views: 174

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533750

You can use either

 MyEnum me = Enum.valueOf(MyEnum.class, word);

or

 MyEnum me = MyEnum.valueof(word)

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245479

You want to use Enum.valueOf:

WhateverEnum.valueOf(someString);

Upvotes: 5

Related Questions