StringToEnumTypeMapper implements TypeMapper<String, T> { @Override public T toJavaType(Column column, Class<?> entityType, String value) { if (value == null) { return null; } else { if (cachedEnum.get() == null) { synchronized (cachedEnum) { if (cachedEnum.get() == null) { cachedEnum.set(enumClass(column, entityType)); } } } final Class<?> enumClass = cachedEnum.get(); final Method fromDatabase; try { fromDatabase = enumClass.getMethod(FROM_DATABASE_METHOD, String.class); } catch (final NoSuchMethodException ex) { throw new IllegalArgumentException("Could not find generated '" + FROM_DATABASE_METHOD + "'-method in enum class '" + enumClass.getName() + "'.", ex); } try { @SuppressWarnings("unchecked") final T result = (T) fromDatabase.invoke(null, value); return result; } catch (final IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new IllegalArgumentException( "Error executing '" + FROM_DATABASE_METHOD + "' in generated enum class '" + enumClass.getName() + "'.", ex ); } } } StringToEnumTypeMapper(); @Override String getLabel(); @Override Type getJavaType(Column column); @Override Category getJavaTypeCategory(Column column); @Override T toJavaType(Column column, Class<?> entityType, String value); @Override String toDatabaseType(T constant); @Inject public Injector injector; }
@Test void toJavaType() { final User.Name actual = instance.toJavaType(column, User.class, "ONE"); assertEquals(User.Name.ONE, actual); assertEquals(User.Name.ONE, instance.toJavaType(column, User.class, "ONE")); }
@Test void toJavaTypeNull() { assertNull(instance.toJavaType(column, User.class, null)); }
@Test void toJavaTypeNoToDatabaseMethod() { final StringToEnumTypeMapper<A.NamE> tm = new StringToEnumTypeMapper<>(); injector.inject(tm); assertThrows(NoSuchElementException.class, () -> tm.toJavaType(column, A.class, "ONE")); }
@Test void toJavaTypeUnableToAccessToDatabaseMethod() { final StringToEnumTypeMapper<B.NaMe> tm = new StringToEnumTypeMapper<>(); injector.inject(tm); assertThrows(IllegalArgumentException.class, () -> tm.toJavaType(column, B.class, "ONE")); }