Java String Value Of valueOf(Class cls, String s)

Here you can find the source of valueOf(Class cls, String s)

Description

value Of

License

Apache License

Declaration

public static <T extends Enum<T>> T valueOf(Class<T> cls, String s) 

Method Source Code

//package com.java2s;
/*/*from   w ww. j  av a 2  s  .  c om*/
 * Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>.
 *
 * 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 {
    public static <T extends Enum<T>> T valueOf(Class<T> cls, String s) {
        try {
            return Enum.valueOf(cls, s);
        } catch (IllegalArgumentException e) {
        }
        s = s.toLowerCase();
        T theOne = null;
        for (T value : cls.getEnumConstants()) {
            if (value.toString().toLowerCase().startsWith(s)) {
                if (theOne == null)
                    theOne = value;
                else
                    throw new IllegalArgumentException("ambiguous value");
            }
        }
        return theOne;
    }
}

Related

  1. valueOf(Class en, String name)
  2. valueOf(Class enumType, String constantName)
  3. valueOf(Class enumType, String name)
  4. valueOf(Class enumType, String name)