Because in many cases, if the data to be converted is NULL, the caller expects the default value to be returned.
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.
To do this, I provide an extension function that gets the default value of the data type
Goal:
1) Implement default values that return basic types according to their needs
2) Not too bad performance
1: interface:
public static <T> T Getdefault (class<t> t)
2: implementation
/** * Gets the default value of the data type * @param t * @return * /@SuppressWarnings ("unchecked") public static <T> T Getdefault (Class<t> t) {if (t = = object.class) {return null;} if (t = = Integer.class) {return t.cast (-1);} if (t = = String.class) {return t.cast ("");} if (t = = Boolean.class) {Object ret = False;return (t) ret;} if (t = = Boolean.class) {Object ret = False;return (t) ret;} if (t = = Bigdecimal.class) {return (T) (New BigDecimal (-1));} Class<?> superclass = T.getsuperclass (), if (superclass = = null) {Object val = -1;return (t) Val;} if (T.getsuperclass (). Equals (Number.class)) {Object val = -1;return (t) Val;} return null; }
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);}
Basic data Type default value extension in Java