Basic data type conversions in Java

Source: Internet
Author: User
Tags assert

If you want to do an ORM and map the data to an object, then the basic data type conversion is the necessary function, and Java does not seem to provide that functionality, only to do it yourself.

The goal of completing this function is as follows:

1: Provide basic data conversion

2: Consider the performance of the conversion.

Here are my specific implementations:

1: interface:

public static <T> T Cast (class<t> T, Object value)

2: Dependency: Need to rely on and get data default value, because in many cases, if the data to be converted is NULL, the caller expects to return the default value.

The default value that is automatically provided by the system does not meet our needs, such as the default value of int is 0, but in SQL queries, if the query fails, we expect a value less than 0, such as select Count (1) from table1.

3: implementation:

/**     * Type conversion     * @param t     * @param value     * @return     *    /@SuppressWarnings ("unchecked") public static <T> T Cast (class<t> T, Object value) {    if (value = = null) {    return Getdefault (t);    } if (t = = Object.class) {return (t) value;} Try{return cast_i (t, value);} catch (Exception ex) {ex.printstacktrace ();    return Getdefault (t);}    }

  

    private static String Getstr (Class<?> T, Object value) {    if (value = = null) {    return "";    }    if (t = = String.class) {return (String) value;  } else {return value.tostring ();  }    }

  

@SuppressWarnings ("unchecked") private static <T> T cast_i (class<t> T, Object value) {class<?> Objcla SS = Value.getclass (), if (t = = String.class) {return (T) getstr (objclass, value);} if (t = = Int.class) {if (objclass = = Int.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = integer.parseint (text);  Return (T) ret;  }if (t = = Integer.class) {if (objclass = = Integer.class) {return (t) value;} if (objclass = = Int.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = integer.parseint (text);  Return (T) ret; }if (t = = Short.class) {if (objclass = = Int.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = short.parseshort (text);  Return (T) ret; }if (t = = Boolean.class | | t = = boolean.class) {if (objclass = = Int.class) {Object ret = (int) value >= 1? true:false;re Turn (T) ret;} if (objclass = = Integer.class) {Object ret = (Integer) value >= 1? True:false;return (T) ret;} String Text = Getstr (objclass, value); Object ret = integer.parseint (text); ret = (int) ret >= 1? True:false;return (T) ret; }if (t = = Long.class) {if (objclass = = Long.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = Long.parselong (text);  Return (T) ret; }if (t = = Byte.class) {if (objclass = = Byte.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = byte.parsebyte (text);  Return (T) ret; }if (t = = Double.class) {if (objclass = = Double.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = double.parsedouble (text);   Return (T) ret; }if (t = = Float.class) {if (objclass = = Float.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = float.parsefloat (text);  Return (T) ret; }if (t = = Bigdecimal.class) {if (objclass = = Bigdecimal.class) {return (t) value;} String Text = Getstr (objclass, value); return (T) new BigDecimal (text); }if (t = = Java.util.Date.class) {if (objclass = = Java.util.Date.class) {return (t) value;} String Text = getstr (objclass, value); return (t) hitypehelper.convert2date (text); }if (t = = Java.sql.Date.class) {if (objclass = = Java.sql.Date.class) {return (t) value;}  String Text = Getstr (objclass, value); return (T) hitypehelper.convert2sqldate (text); }if (t = = Time.class) {if (objclass = = Time.class) {return (t) value;}  String Text = Getstr (objclass, value); Object ret = hitypehelper.convert2date (text). GetTime ();  Return (T) ret; }if (t = = Timestamp.class) {if (objclass = = Timestamp.class) {return (t) value;}  String Text = Getstr (objclass, value); return (T) timestamp.valueof (text); }return (T) value;}

  

3: Test Code:

@Testpublic void Test_hitypehelper_cast () {Integer val = 1;int ret = Hitypehelper.cast (Int.class, Val); Assert.assertequals (ret, 1); String Text = "1"; ret = Hitypehelper.cast (int.class, text); Assert.assertequals (ret, 1); text = "a"; ret = Hitypehelper.cast (int.class, text); Assert.assertequals (ret,-1); int val2 = 1;integer Ret2 = Hitypehelper.cast (Integer.class, val2); Assert.assertequals (Ret2.intvalue (), 1); text = "1"; Ret2 = Hitypehelper.cast (integer.class, text); Assert.assertequals (Ret2.intvalue (), 1); Boolean bl = Hitypehelper.cast (Boolean.class, 1); Assert.asserttrue (BL); bl = Hitypehelper.cast (Boolean.class, 3); Assert.asserttrue (BL); bl = hitypehelper.cast (boolean.class, 0); Assert.assertfalse (BL); bl = Hitypehelper.cast (Boolean.class,-1); Assert.assertfalse (BL); BL = Hitypehelper.cast (Boolean.class, "1"); Assert.asserttrue (BL); bl = Hitypehelper.cast (Boolean.class, "3"); Assert.asserttrue (BL); bl = Hitypehelper.cast (Boolean.class, "0"); Assert.assertfalse (BL); bl = Hitypehelper.cast (Boolean.class, "-1"); Assert.assertfalse (BL);}

  

Many times, data transformations are used more when interacting with the database, so there is a need to provide some conversion of the database types, mainly referring to time or date conversions. For example: Java.util.date,java.sql.date and string and long, here is my implementation:

    /** * String converted to date * @param text * @return */public static java.util.Date Convert2date (string text) {     if (text = = NULL | | Text.trim () = = "") {return null; }string format = "YYYY-MM-DD"; String str = Text.trim (), if (Str.contains (":")) {format = "Yyyy-mm-dd HH:mm:ss";}  SimpleDateFormat SDF = new SimpleDateFormat (format); try {return sdf.parse (str);} catch (ParseException e) {//TODO auto-generated catch Blocke.printstacktrace (); return null; }}/** * string converted to date * @param text * @return */public static java.sql.Date Convert2sqldate (Str    ing text) {java.util.Date dt = convert2date (text); return new Java.sql.Date (Dt.gettime ()); /** * Date converted to String * @param date * @return */public static string toshortstring (Java.util.Dat    E date) {if (date = = null) {return null;  }simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd");    return Sdf.format (date);     }/** * Date converted to String * @param date* @return */public static String tolongstring (java.util.Date date) {if (date = = null) {return null;  }simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");    return Sdf.format (date);     }/** * Date converted to String * @param date * @return */public static string toshortstring (Java.sql.Date date) {    if (date = = null) {return null;  }simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd");    return Sdf.format (date); /** * Date converted to String * @param date * @return */public static string tolongstring (java.sql.Date date    {if (date = = null) {return null;  }simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");    return Sdf.format (date); }

  

Basic data type conversions in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.