EnumConverter implements Converter { @SuppressWarnings({"unchecked", "rawtypes"}) public Object convert(Class destClass, Object srcObj) { if (null == srcObj) { MappingUtils.throwMappingException("Cannot convert null to enum of type " + destClass); } try { if ((srcObj.getClass().equals(Byte.class)) || (srcObj.getClass().equals(Byte.TYPE))) { return EnumUtils.getEnumList(destClass).get(((Byte)srcObj).intValue()); } else if ((srcObj.getClass().equals(Short.class)) || (srcObj.getClass().equals(Short.TYPE))) { return EnumUtils.getEnumList(destClass).get(((Short)srcObj).intValue()); } else if ((srcObj.getClass().equals(Integer.class)) || (srcObj.getClass().equals(Integer.TYPE))) { return EnumUtils.getEnumList(destClass).get((Integer)srcObj); } else if ((srcObj.getClass().equals(Long.class)) || (srcObj.getClass().equals(Long.TYPE))) { return EnumUtils.getEnumList(destClass).get(((Long) srcObj).intValue()); } else if (Enum.class.isAssignableFrom(srcObj.getClass())) { return Enum.valueOf(destClass, ((Enum)srcObj).name()); } else { return Enum.valueOf(destClass, srcObj.toString()); } } catch (Exception e) { MappingUtils.throwMappingException("Cannot convert [" + srcObj + "] to enum of type " + destClass, e); } return srcObj; }  @SuppressWarnings({"unchecked", "rawtypes"}) Object convert(Class destClass, Object srcObj);  }
@Test public void canConvertEnumWithOverriddenToStringSameType() { assertEquals(Type.ONE, new EnumConverter().convert(Type.class, Type.ONE)); assertEquals(Type.TWO, new EnumConverter().convert(Type.class, Type.TWO)); }
@Test public void canConvertEnumWithOverriddenToStringDifferentTypes() { assertEquals(AlsoType.ONE, new EnumConverter().convert(AlsoType.class, Type.ONE)); assertEquals(AlsoType.TWO, new EnumConverter().convert(AlsoType.class, Type.TWO)); }