Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

Single Converter for multiple types in Spring (MVC)

I have multiple classes all extended from a specific class, and I want to implement a single Converter for all of them, this is my case:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public abstract class EntityId implements Serializable {
    private Long id;
}


public class Entity1Id extend EntityId {}

public class Entitty2Id extends EntityId {}

now I need to implement a single converter to convert a String came from HttpServletRequest to one specific type in my Model. The problem is Converter.convert() just takes single parameter, is there any alternative to have 2 parameters (input type and the expected result type)?

Upvotes: 1

Views: 527

Answers (1)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

The solution is using a ConverterFactory such as

public final class EntityIdConverterFactory implements ConverterFactory<String, EntityId> {

    @Override
    public <T extends EntityId> Converter<String, T> getConverter(final Class<T> targetType) {
        return new StringToEntityIdConverter<>(targetType);
    }

    private static final class StringToEntityIdConverter<T extends EntityId> implements Converter<String, T> {
        private final Class<? extends T> targetType;

        StringToEntityIdConverter(final Class<? extends T> targetType) {
            this.targetType = targetType;
        }

        @Nullable
        @Override
        public T convert(final String source) {
            if (StringUtils.isEmpty(source)) {
                return null;
            }

            try {
                final T t = targetType.newInstance();
                t.setId(Long.parseLong(source));
                return t;
            } catch (final Exception e) {
                ReflectionUtils.handleReflectionException(e);
            }
            throw new AssertionError("Never reach here!");
        }
    }
}

Upvotes: 1

Related Questions