0

i have a enum

public enum Category {
NonResidential("Non-Residential"), Residential("Residential");
private String category;

BuildingAssetCategory(String s) {
    category = s;
}

public String getType() {
    return category;
}

public void setType(String type) {
    this.category = type;
}
}

I want to get the enum on the basis of value its having. i have String of value Non-Residential, then how can i get the enum returning `NonResidential.

P.S i to want to create own magic rather then something java supports. i have read out many question like this but i want different ans.

Community
  • 1
  • 1
Sindhoo Oad
  • 1,194
  • 2
  • 13
  • 29

2 Answers2

3

There is no magic here, since it's your own define field ('category') you should write your own static method to search by it. For example:

public enum Category {
  ...
        public static Category findByName(String cat){
            // loop over Category.values() and find the requested cat
        }

btw ValueOf will work if you provide the enum name (e.g. "NonResidential") but it won't work for category name (e.g. "non-residential")

Pelit Mamani
  • 2,321
  • 2
  • 13
  • 11
0

Use valueOf.

Category.valueOf("Non-Residential");

This will return you the enum.

Pramod Karandikar
  • 5,289
  • 7
  • 43
  • 68
  • same punch, I have also done this but unfortunately it returns `java.lang.IllegalArgumentException: No enum constant` :( – Sindhoo Oad Mar 27 '15 at 04:11