Java Object Type Case castValue(String value, Class clazz)

Here you can find the source of castValue(String value, Class clazz)

Description

cast Value

License

Open Source License

Declaration

public static <T> T castValue(String value, Class<T> clazz) 

Method Source Code

//package com.java2s;

public class Main {
    public static <T> T castValue(String value, Class<T> clazz) {
        if (clazz == String.class) {
            if (value == null) {
                return null;
            }/*from  ww w  .  j  a va 2 s.c om*/

            return (T) value;
        } else if (clazz == Integer.class) {
            return (T) toInteger(value);
        } else if (clazz == Long.class) {
            return (T) toLongAsObject(value);
        } else if (clazz == Boolean.class) {
            if (value == null) {
                return (T) new Boolean(false);
            }

            return (T) Boolean.valueOf(value);
        }

        return null;
    }

    public static Integer toInteger(Object obj) {
        if (obj != null) {
            if (obj instanceof Integer) {
                return (Integer) obj;
            } else {
                try {
                    return Integer.parseInt(String.valueOf(obj));
                } catch (Exception e) {
                }
            }
        }

        return null;
    }

    public static Long toLongAsObject(Object obj) {
        if (obj != null) {
            if (obj instanceof Long) {
                return (Long) obj;
            } else {
                try {
                    return Long.parseLong(String.valueOf(obj));
                } catch (Exception e) {
                }
            }
        }

        return null;
    }
}

Related

  1. castToObject(Object value)
  2. castToPrimitive(Object value, String targetType)
  3. castTotal(boolean isDoubleQuote, String target)
  4. castToTypeOrNull(Object object, Class clazz)
  5. castUnderLine(String origin)
  6. castWithGenericsOrNull(Class base, Object obj)