Java Class Load fromString(Class enumClass, String s, T defaultValue)

Here you can find the source of fromString(Class enumClass, String s, T defaultValue)

Description

Returns the enum constant that matches the specified string, or the default value if none of the constants matches or if the string is null.

License

Open Source License

Parameter

Parameter Description
T the enum type
enumClass the class object for the enum type
s the string that specifies a constant
defaultValue the default value to use if none of the constants matches or if s is null

Return

the matching constant or the default value

Declaration

public static final <T extends Enum<T>> T fromString(Class<T> enumClass, String s, T defaultValue) 

Method Source Code

//package com.java2s;
/**/*from ww w. j  av a  2  s. com*/
 * Copyright (c) 2010 Martin Geisse
 *
 * This file is distributed under the terms of the MIT license.
 */

public class Main {
    /**
     * Returns the enum constant that matches the specified string, or the default value if
     * none of the constants matches or if the string is null.
     * @param <T> the enum type
     * @param enumClass the class object for the enum type
     * @param s the string that specifies a constant
     * @param defaultValue the default value to use if none of the constants matches or if s is null
     * @return the matching constant or the default value
     */
    public static final <T extends Enum<T>> T fromString(Class<T> enumClass, String s, T defaultValue) {
        try {
            return Enum.valueOf(enumClass, s);
        } catch (IllegalArgumentException e) {
            return defaultValue;
        } catch (NullPointerException e) {
            return defaultValue;
        }
    }
}

Related

  1. classForNameOrNull(final String className)
  2. classForNameOrPrimitive(String name, ClassLoader loader)
  3. fromString(Class clazz, String stringValue)
  4. fromString(Class clazz, String name)
  5. fromString(Class clz, String value, T defaultVal)
  6. fromString(Class enumType, String text)
  7. fromString(final Class clazz, final String value)
  8. fromString(String string, Class arrayClass)
  9. getClass(Class clazz)