Convert primitive back and forth : Primitive Data Type « Data Type « Java

Convert primitive back and forth


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;


Related examples in the same category

1.Use Integer constructor to convert int primitive type to Integer object.
2.Convert Java Integer object to Numeric primitive types
3.Convert Java String to Integer object
4.Create an Integer object
5.Arithmetic DemoArithmetic Demo
6.Max Variable Length DemoMax Variable Length Demo
7.Data Type Print TestData Type Print Test
8.Tests all the operators on all the primitive data types
9.Demonstrates the ++ and -- operatorsDemonstrates the ++ and -- operators
11.Demonstrates the mathematical operators.Demonstrates the mathematical operators.
12.Java lets you overflowJava lets you overflow
13.Built in typesBuilt in types
14.Shows default initial valuesShows default initial values
15.Relational DemoRelational Demo
16.Parse Number
17.Java Type Helper
18.Convert the given array (which may be a primitive array) to an object array
19.Returns a default value if the object passed is null
20.A mutable boolean wrapper.
21.A mutable byte wrapper.
22.A mutable double wrapper.
23.A mutable float wrapper.
24.A mutable int wrapper.
25.A mutable long wrapper.
26.A mutable short wrapper.
27.Primitive utilities