Java Integer Create toInt(Object o, int defaultValue)

Here you can find the source of toInt(Object o, int defaultValue)

Description

to Int

License

LGPL

Declaration

public static int toInt(Object o, int defaultValue) 

Method Source Code

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

public class Main {
    public static int toInt(Object o, int defaultValue) {
        if (o == null)
            return defaultValue;

        if (o.getClass() == Integer.class)
            return (Integer) o;

        if (o.getClass() == Boolean.class)
            return booleanToInt((Boolean) o);
        if (o.getClass() == Byte.class)
            return (int) ((Byte) o).byteValue();
        if (o.getClass() == Character.class)
            return (int) ((Character) o).charValue();
        if (o.getClass() == Short.class)
            return (int) ((Short) o).shortValue();
        if (o.getClass() == Long.class)
            return longToInt((Long) o, defaultValue);
        if (o.getClass() == Float.class)
            return floatToInt((Float) o, defaultValue);
        if (o.getClass() == Double.class)
            return doubleToInt((Double) o, defaultValue);
        if (o.getClass() == String.class)
            return stringToInt((String) o, defaultValue);

        return defaultValue;
    }/*from  w  w  w  .j a  va  2 s.  c  o  m*/

    public static int booleanToInt(boolean b) {
        return b ? 1 : 0;
    }

    public static int longToInt(long l, int defaultValue) {
        if (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) {
            return (int) l;
        }
        return defaultValue;
    }

    public static int floatToInt(float f, int defaultValue) {
        if (f >= Integer.MIN_VALUE && f <= Integer.MAX_VALUE) {
            return (int) f;
        }
        return defaultValue;
    }

    public static int doubleToInt(double d, int defaultValue) {
        if (d >= Integer.MIN_VALUE && d <= Integer.MAX_VALUE) {
            return (int) d;
        }
        return defaultValue;
    }

    public static int stringToInt(String s, int defaultValue) {
        try {
            return Integer.valueOf(s);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
}

Related

  1. toInt(Number wrapped)
  2. toInt(Object bean, int defaultValue)
  3. toInt(Object num)
  4. toInt(Object num, int defValue)
  5. toInt(Object o)
  6. toInt(Object obj)
  7. toInt(Object obj)
  8. toInt(Object obj)
  9. toInt(Object obj)