Java Reflection Primitive toPrimitive(String primitiveJson, Class clazz)

Here you can find the source of toPrimitive(String primitiveJson, Class clazz)

Description

to Primitive

License

Apache License

Declaration

public static <T> T toPrimitive(String primitiveJson, Class<T> clazz) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.HashMap;
import java.util.Map;

public class Main {
    private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>();

    public static <T> T toPrimitive(String primitiveJson, Class<T> clazz) {
        Object result = null;//from  w  w  w . j a  va 2  s .  c  o  m

        if (clazz.isAssignableFrom(int.class)) {
            result = Integer.parseInt(primitiveJson);

        } else if (clazz.isAssignableFrom(long.class)) {
            result = Long.parseLong(primitiveJson);

        } else if (clazz.isAssignableFrom(short.class)) {
            result = Short.parseShort(primitiveJson);

        } else if (clazz.isAssignableFrom(float.class)) {
            result = Float.parseFloat(primitiveJson);

        } else if (clazz.isAssignableFrom(double.class)) {
            result = Double.parseDouble(primitiveJson);

        } else if (clazz.isAssignableFrom(byte.class)) {
            result = Byte.parseByte(primitiveJson);

        } else if (clazz.isAssignableFrom(boolean.class)) {
            result = Boolean.parseBoolean(primitiveJson);

        } else if (clazz.isAssignableFrom(char.class)) {
            result = primitiveJson.charAt(0);

        } else if (clazz.isAssignableFrom(Void.TYPE)) {
            result = "";
        }

        Class<?> wrapper = primitiveWrapperMap.get(clazz);

        return (T) wrapper.cast(result);
    }
}

Related

  1. resolveClassPrimitiveAware(String className)
  2. resolvePrimitiveClassName(String name)
  3. resolvePrimitiveClassName(String name)
  4. resolvePrimitiveIfNecessary(Class clazz)
  5. resolvePrimitiveType(Class clazz)
  6. unwrapPrimitive(final Class clazz)