Convert primitive back and forth : Data Type Conversion « Data Type « Java Tutorial






public final class PrimitiveUtils {

    
    public static Class getClass(String value) {
        Class clz = null;        
        if ("int".equals(value)) {
            clz = int.class;
        }
        if ("byte".equals(value)) {
            clz = byte.class;
        }
        if ("short".equals(value)) {
            clz = short.class;
        }
        if ("long".equals(value)) {
            clz = long.class;
        }
        if ("float".equals(value)) {
            clz = float.class;
        }
        if ("double".equals(value)) {
            clz = double.class;
        }
        if ("boolean".equals(value)) {
            clz = boolean.class;
        }
        if ("char".equals(value)) {
            clz = char.class;
        }
        return clz;
    }

    public static Object read(String value, Class type) {
        Object ret = value;
        if (Integer.TYPE.equals(type)) {
            ret = Integer.valueOf(value);
        }
        if (Byte.TYPE.equals(type)) {
            ret = Byte.valueOf(value);
        }
        if (Short.TYPE.equals(type)) {
            ret = Short.valueOf(value);
        }
        if (Long.TYPE.equals(type)) {
            ret = Long.valueOf(value);
        }
        if (Float.TYPE.equals(type)) {
            ret = Float.valueOf(value);
        }
        if (Double.TYPE.equals(type)) {
            ret = Double.valueOf(value);
        }
        if (Boolean.TYPE.equals(type)) {
            ret = Boolean.valueOf(value);
        }
        if (Character.TYPE.equals(type)) {
            ret = value.charAt(0);
        }
        // TODO others.
        return ret;
    }
}








2.16.Data Type Conversion
2.16.1.The Widening Conversion
2.16.2.The Narrowing Conversion
2.16.3.Narrowing conversion with information loss
2.16.4.An automatic type conversion
2.16.5.Casting Incompatible Types
2.16.6.Pass a string to the Integer class constructor and call the intValue()
2.16.7.Use toString method of Integer class to conver Integer into String.
2.16.8.Declaring Checked Exceptions
2.16.9.Automatic Type Promotion in Expressions
2.16.10.Convert byte array to Integer and Long
2.16.11.Class with methods for type conversion
2.16.12.Data type conversion
2.16.13.Convert primitive back and forth