Java String to convertStringToValue(String txt, Class klass)

Here you can find the source of convertStringToValue(String txt, Class klass)

Description

convert String To Value

License

Open Source License

Declaration

public static Object convertStringToValue(String txt, Class<?> klass) 

Method Source Code

//package com.java2s;
/*/*  w ww . ja v a  2s . co m*/
  PropertyUtils.java
    
  (c) 2010-2013 Edward Swartz
    
  All rights reserved. This program and the accompanying materials
  are made available under the terms of the Eclipse Public License v1.0
  which accompanies this distribution, and is available at
  http://www.eclipse.org/legal/epl-v10.html
 */

public class Main {
    public static Object convertStringToValue(String txt, Class<?> klass) {
        Object v = null;
        try {
            if (klass.equals(Double.class) || klass.equals(Double.TYPE))
                v = Double.parseDouble(txt);
            else if (klass.equals(Float.class) || klass.equals(Float.TYPE))
                v = Float.parseFloat(txt);
            else if (klass.equals(Integer.class) || klass.equals(Integer.TYPE))
                v = Integer.parseInt(txt);
            else if (klass.equals(String.class))
                v = txt;
            else if (klass.equals(Boolean.class) || klass.equals(Boolean.TYPE))
                v = Boolean.parseBoolean(txt);
            else if (klass.isEnum()) {
                for (Object val : klass.getEnumConstants()) {
                    if (val.toString().equals(txt)) {
                        v = val;
                        break;
                    }
                }
                if (v == null) {
                    new IllegalStateException("invalid enum " + txt + " for " + klass).printStackTrace();
                }

            } else {
                throw new IllegalStateException("not handled: " + klass);
            }
            return v;
        } catch (NumberFormatException e2) {
            return null;
        }
    }
}

Related

  1. convertStringToObject(String value, Class type)
  2. convertStringToPrimaryKey(String keyString)
  3. convertStringToPrimitive(Object object, Class toType)
  4. convertStringToPrimitive(String value, Class destinationClass)
  5. convertStringToSafeFilename(String s)
  6. convertStringToVarName(final String str)
  7. convertStringToWord(String strValue)
  8. convertStringWithReplacementPattern(final String originalString, final String pattern, final String replace)