Here you can find the source of valueOfNullSafe(final Class
Parameter | Description |
---|---|
enumType | the Class object of the enum type from which to return a constant |
name | the name of the constant to return |
null
if not found
public static <E extends Enum<E>> E valueOfNullSafe(final Class<E> enumType, final String name)
//package com.java2s; /**/*from w ww.j av a 2 s. c o m*/ * Copyright (C) [2013] [The FURTHeR Project] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * Returns the enum constant of the specified enum type with the specified name. The * name must match exactly an identifier used to declare an enum constant in this * type. If it does not, this method returns <code>null</code>. * * @param enumType * the Class object of the enum type from which to return a constant * @param name * the name of the constant to return * @return the enum constant of the specified enum type with the specified name or * <code>null</code> if not found * @see {link Enum.valueOf} */ public static <E extends Enum<E>> E valueOfNullSafe(final Class<E> enumType, final String name) { try { return Enum.valueOf(enumType, name); } catch (final IllegalArgumentException e) { return null; } catch (final NullPointerException e) { return null; } } /** * Returns the enum constant of the specified enum type with the specified name. The * name must match exactly an identifier used to declare an enum constant in this * type. If it does not, this method returns <code>null</code>. * * @param enumType * the Class object of the enum type from which to return a constant * @param name * the name of the constant to return * @return the enum constant of the specified enum type with the specified name or * <code>null</code> if not found * @see {link Enum.valueOf} */ public static <E extends Enum<E>> E valueOfNullSafe(final Class<E> enumType, final Object object) { return (object == null) ? null : valueOfNullSafe(enumType, object.toString()); } /** * Convert a string to an enum. Encapsulates unchecked warning suppression. * * @param enumType * @param value * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Enum<?> valueOf(final Class<?> enumType, final String value) { return Enum.valueOf((Class<Enum>) enumType, value); } }