ValueConverter { @SuppressWarnings("unchecked") public static <T> T convert(Object value, Class<T> classTo) { if(value != null) { if(String.class.isAssignableFrom(classTo)) { return (T) value.toString(); } else if(Long.class.isAssignableFrom(classTo)) { if(value instanceof Number) { return (T)new Long(((Number)value).longValue()); } else if(value instanceof String){ return (T)new Long(Long.parseLong((String)value)); } else { throw unsupportedConversionException(classTo, value); } } else if(Integer.class.isAssignableFrom(classTo)) { if(value instanceof Number) { return (T)new Integer(((Number)value).intValue()); } else if(value instanceof String){ return (T)new Integer(Integer.parseInt((String)value)); } else { throw unsupportedConversionException(classTo, value); } } else { throw unsupportedConversionException(classTo, value); } } else { return null; } }  @SuppressWarnings("unchecked") static T convert(Object value, Class<T> classTo);  }
@Test public void test() { Object value; value = ValueConverter.convert("1", Long.class); assertEquals(Long.class, value.getClass()); assertEquals(1, (long) value); value = ValueConverter.convert(1l, Long.class); assertEquals(Long.class, value.getClass()); assertEquals(1, (long) value); value = ValueConverter.convert(1, Long.class); assertEquals(Long.class, value.getClass()); assertEquals(1, (long) value); value = ValueConverter.convert(1.1, Long.class); assertEquals(Long.class, value.getClass()); assertEquals(1, (long) value); value = ValueConverter.convert("1", Integer.class); assertEquals(Integer.class, value.getClass()); assertEquals(1, (int) value); value = ValueConverter.convert(1, Integer.class); assertEquals(Integer.class, value.getClass()); assertEquals(1, (int) value); value = ValueConverter.convert("1", String.class); assertEquals(String.class, value.getClass()); assertEquals("1", value); }