0

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 type TestCase.Test is not applicable for the arguments (String).

How can I convert the value or set it to the createTest method?

4
  • What is the actual value in the JSON? What is the complete, compilable code of the enum? Commented Mar 7, 2014 at 12:16
  • The above code doesn't compile, you need to change the enum code to public enum OwnerType { User, Role; } or you need a constructor for OwnerType that takes a String-typed argument. Commented Mar 7, 2014 at 12:22
  • Yes. The constructor I have like private final String value;private OwnerType(String value) {this.value = value;} Commented Mar 7, 2014 at 12:27
  • Ok. You can already get the name of the enum using m_ownerType.name() or m_ownerType.toString() (check Javadoc for when to use which) Commented Mar 7, 2014 at 12:30

2 Answers 2

1

You have to use the OwnerType#valueOf(String name) method :

String name = JSONUtil.getStringValue(obj, JSON_KEY);
test.setOwnerType(Test.OwnerType.valueOf(name));
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.