0

I have defined an enum as follows:

public enum TileTypes
{
    DESERT, GRASS, HILL, MOUNTAIN, OCEAN, RIVEREE, RIVEREN, RIVERES, RIVERNE, RIVERNS, RIVERNW, RIVERSE, RIVERSS, RIVERSW,
    RIVERWN, RIVERWS, RIVERWW, SWAMP

}

I read data from XML where I refer to that enum as described below:

<tile>
        <id>1</id>
        <type>GRASS</type>
        <x>0</x>
        <y>0</y>
        <east>2</east>
        <south>4</south>
</tile>

I have an XML parser class which does the following (excerped):

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
        {
            if (qName.equalsIgnoreCase("type"))
            {
                type = true;
    }
    }
public void endElement(String uri, String localName, String qName) throws SAXException
    {
     if (type)
         {
            //TileTypes.valueOf(data.toString()).);
             //how?
         maptile.setType(TileTypes.GRASS);

        }
    }

Of course I could do a String compare:

if data.toString().equals("GRASS")  
{
    maptile.setType(TileTypes.GRASS); 
}
[...]

and do this for every type of enum, but that does not strike me as the best way: its a lot of conditional statements and not easily extendable.
So is there a way to cast the string value directly into the correct value of the enum?
If that has been answered before, please feel free to point me in the correct direction.

Snorik
  • 201
  • 3
  • 15
  • 2
    https://howtodoinjava.com/java/enum/java-enum-string-example/ – PM 77-1 Apr 21 '20 at 21:47
  • 1
    [`TileTypes.valueOf(...)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#valueOf-java.lang.Class-java.lang.String-) (specifically the paragraph starting "Note that for a particular enum type T") (you need to handle the case of it being invalid). – Andy Turner Apr 21 '20 at 21:51

0 Answers0