Matching enum value to String representation

Discussion in 'Plugin Development' started by Rixterz, Apr 30, 2017.

Thread Status:
Not open for further replies.
  1. Offline

    Rixterz

    Hi,

    Let's say I have the following:

    Code:
    EntityType type = EntityType.ENDERMAN;
    
    String stringRepresentation = type.name();
    
    Then, regardless which enum I use, whether that would be EntityType, Action, ChatColor, anything really, how can I do something like the following to retrieve the EntityType (or whichever enum) again?
    Code:
    // this is the general idea
    EntityType retrievedType = matchEnum(EntityType.class, stringRepresentation);
    
    Example match function for EntityType ONLY, how can I make it return a different enum based on the given parameter?
    Code:
    private EntityType matchEntityType(String s)
        {
            for(EntityType type : EntityType.values())
            {
                if(type.name().equals(s)) return type;
            }
           
            return null;
        }
    This is so I don't have to have several match functions for different enums. I'm not too clued up on Generics.

    Thanks,

    Rix
     
  2. Offline

    Sethburster

    Hello, Have you tried using the static method of EntityType.valueof(String).
    This should return any Enum by a string passed in.


    Sent from my iPhone using Tapatalk
     
  3. Offline

    Rixterz

    I mean I want to pass the enum type as a parameter, then get the value from that
     
  4. Offline

    Sethburster

    I'm a bit confused on what you need. Let me give an example of how the valueOf method would work, and tell me if what you need is something different.

    Say when used with ChatColor,
    If you did ChatColor.valueOf("RED"), it would return you the Enum ChatColor.RED , this would work with any other color you put on that string.

    You could do the same with EntityType using EntityType.valueOf("Enderman").

    Sent from my iPhone using Tapatalk
     
  5. Offline

    Rixterz

    Yes, I know that, but I want the function to take the enum type as a parameter, then return (the given enum).valueOf(s)
     
  6. Offline

    ipodtouch0218

    @Rixterz
    That would require reflection to get the class of the enum, or you can hardcode in "ChatColor" to equal the ChatColor enum.
     
  7. Online

    timtower Administrator Administrator Moderator

    @Rixterz Generics is the best way in my opinion. Then you have solid return types and then you don't have to cast all the time.
     
Thread Status:
Not open for further replies.

Share This Page