You have to use the OwnerType#valueOf(String name)
method :
String name = JSONUtil.getStringValue(obj, JSON_KEY);
test.setOwnerType(Test.OwnerType.valueOf(name));
Question
I have a class TestCase
. Inside of this I have the inner class Test
. Inside the class enum OwnerType
are setters and getters of the enum.
public static final class Test{
public enum OwnerType {
User("User"),
Role("Role");
}
public OwnerType getOwnerType() {
return m_ownerType;
}
public void setOwnerType(OwnerType m_ownerType) {
this.m_ownerType = m_ownerType;
}
}
Test
is the inner class in my case. I am trying to set the value with JSON key
private Test createTest(JSONObject obj) {
Test test = new Test();
test.setOwnerType(JSONUtil.getStringValue(obj, JSON_KEY)); // Gives error
return test;
}
It gives an error
The method
setOwnerType(TestCase.Test.OwnerType)
in the typeTestCase.Test
is not applicable for the arguments (String
).
How can I convert the value or set it to the createTest
method?
Solution
You have to use the OwnerType#valueOf(String name)
method :
String name = JSONUtil.getStringValue(obj, JSON_KEY);
test.setOwnerType(Test.OwnerType.valueOf(name));
OTHER TIPS
You have to parse it into an enum
first.
Try this instead:
test.setOwnerType(Test.OwnerType.valueOf(JSONUtil.getStringValue(obj, JSON_KEY)));
Note that you can either do Enum.valueOf(YourEnum.class, stringValue)
and YourEnum.valueOf(stringValue)
.