Java - Convert String to enum

 

http://stackoverflow.com/questions/604424/java-convert-string-to-enum

 

/**
 * A common method for all enums since they can't have another base class
 * @param  Enum type
 * @param c enum type. All enums must be all caps.
 * @param string case insensitive
 * @return corresponding enum, or null
 */
public static > T getEnumFromString(Class c, String string)
{
    if( c != null && string != null )
    {
        try
        {
            return Enum.valueOf(c, string.trim().toUpperCase());
        }
        catch(IllegalArgumentException ex)
        {
        }
    }
    return null;
}
 

你可能感兴趣的:(J2SE)