Java Reflection Primitive castToPrimitive(Object start, Class prim)

Here you can find the source of castToPrimitive(Object start, Class prim)

Description

cast To Primitive

License

Apache License

Declaration

@SuppressWarnings("unchecked")
    public static <T> T castToPrimitive(Object start, Class<T> prim) 

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<?>, Object> defaultPrimitiveValues = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static <T> T castToPrimitive(Object start, Class<T> prim) {
        try {/*from  w  w w .  j  av a 2 s.c  o  m*/
            if (start == null) {
                return (T) defaultPrimitiveValues.get(prim);
            }
            if (start instanceof Boolean) {
                start = ((Boolean) start) ? 1 : 0;
            }
            if (start instanceof Character) {
                start = (int) ((Character) start).charValue();
            }
            if (prim == char.class) {
                return (T) Character.valueOf((char) ((Number) start).intValue());
            }
            switch (prim.getName()) {
            case "int":
                return (T) (Object) ((Number) start).intValue();
            case "long":
                return (T) (Object) ((Number) start).longValue();
            case "short":
                return (T) (Object) ((Number) start).shortValue();
            case "double":
                return (T) (Object) ((Number) start).doubleValue();
            case "float":
                return (T) (Object) ((Number) start).floatValue();
            case "byte":
                return (T) (Object) ((Number) start).byteValue();
            case "boolean":
                return (T) (Object) (((Number) start).intValue() != 0 ? true : false);
            default:
                throw new IllegalArgumentException(prim.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) start;
    }
}

Related

  1. addPrimitiveToWrapperRelation(Class primitiveClass, Class wrapperClass)
  2. calculateDistancePrimitive(Class a, Class b)
  3. canCoerceLiteralNumberExpr(Class type)
  4. convertPrimitiveToObjectClass(Class clazz)
  5. convertPrimitiveToWrapper(Class clazz)
  6. convertPrimitiveToWrapper(Class clazz)
  7. convertToPrimitive(Class type)