NumberType implements Type<NumberHolder> { @Override public NumberHolder convert(Object obj) { if (obj instanceof Number) { Number n = (Number) obj; BigDecimal result; if (n instanceof Double || n instanceof Float) { result = new BigDecimal(n.doubleValue()); } else if (n instanceof BigDecimal) { result = (BigDecimal) n; } else if (n instanceof BigInteger) { result = new BigDecimal((BigInteger) n); } else { result = new BigDecimal(n.longValue()); } return new NumberHolder(result); } if (obj == null) { return new NumberHolder(null); } if (obj instanceof String) { return decode((String) obj); } throw new IllegalArgumentException("conversion not supported for: " + obj.getClass()); }  @Override String encode(NumberHolder value); @Override NumberHolder decode(String text); @Override NumberHolder convert(Object obj); @Override NumberHolder[] newArray(int size); static final String TYPE_NAME; }
@Test public void testConvert() { Object[][] testCases = { {new Long(17), new BigDecimal("17")}, {new Integer(50), new BigDecimal("50")}, {new Double(0.12345), new BigDecimal(0.12345)}, {new Float(0.12345), new BigDecimal(0.12345f)}, {(byte) 100, new BigDecimal(100)}, {(short) 2000, new BigDecimal(2000)}, {(float) 123, new BigDecimal(123f)}, {null, null}, {"", null}, {" ", null}, {"123,45", new BigDecimal("123.45")}, {new BigInteger("1234"), new BigDecimal(1234)}, {new BigDecimal("00.12"), new BigDecimal("00.12")}, {String.valueOf(Long.MIN_VALUE), new BigDecimal(Long.MIN_VALUE)}, {String.valueOf(Long.MAX_VALUE), new BigDecimal(Long.MAX_VALUE)} }; for (Object[] testCase : testCases) { Object obj = testCase[0]; BigDecimal expectedValue = (BigDecimal) testCase[1]; assertEquals(expectedValue, type.convert(obj).getBigDecimal()); assertEquals(expectedValue, type.convert(obj).getValue()); } }
@Test public void testConvert__illegalArgument() { Object[] illegals = {new Date(), new int[0], "abc"}; for (Object obj : illegals) { try { type.convert(obj); fail(); } catch (RuntimeException e) { assertTrue(e instanceof IllegalArgumentException || e instanceof NumberFormatException); } } }