/** * Produce a Number which represents the given value {@code x} according to the primitive type of * the given wrapper {@code wrap}. Caller must invoke intValue, byteValue, longValue (etc.) on the * result to retrieve the desired primitive value. */ public static Number primitiveConversion(Wrapper wrap, Object x, boolean cast) { // Maybe merge this code with Wrapper.convert/cast. Number res; if (x == null) { if (!cast) return null; return ZERO_INT; } if (x instanceof Number) { res = (Number) x; } else if (x instanceof Boolean) { res = ((boolean) x ? ONE_INT : ZERO_INT); } else if (x instanceof Character) { res = (int) (char) x; } else { // this will fail with the required ClassCastException: res = (Number) x; } Wrapper xwrap = Wrapper.findWrapperType(x.getClass()); if (xwrap == null || !cast && !wrap.isConvertibleFrom(xwrap)) // this will fail with the required ClassCastException: return (Number) wrap.wrapperType().cast(x); return res; }