I'm playing around with Spring's ConversionService
, adding a simple converter to convert a ZonedDateTime
(Java 8) to String
:
@Bean
public ConversionServiceFactoryBean conversionServiceFactoryBean() {
ConversionServiceFactoryBean conversionServiceFactoryBean =
new ConversionServiceFactoryBean();
Converter<ZonedDateTime, String> dateTimeConverter =
new Converter<ZonedDateTime, String>() {
@Override
public String convert(ZonedDateTime source) {
return source.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
};
conversionServiceFactoryBean.setConverters(
new HashSet<>(Arrays.asList(dateTimeConverter)));
return conversionServiceFactoryBean;
}
This works fine. But my IDE (IntelliJ) suggests replacing the anonymous inner class with a lambda expression:
Converter<ZonedDateTime, String> dateTimeConverter =
source -> source.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
If I do that, then it doesn't work anymore, I get an error about Spring not being able to determine the generic types:
Caused by: java.lang.IllegalArgumentException: Unable to the determine sourceType <S> and targetType <T> which your Converter<S, T> converts between; declare these generic types.
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.core.convert.support.GenericConversionService.addConverter(GenericConversionService.java:100)
at org.springframework.core.convert.support.ConversionServiceFactory.registerConverters(ConversionServiceFactory.java:50)
at org.springframework.context.support.ConversionServiceFactoryBean.afterPropertiesSet(ConversionServiceFactoryBean.java:70)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564)
The Class
object that represents the lambda expression is apparently different enough from the Class
for the anonymous inner class that Spring can't determine the generic types anymore. How does Java 8 do this exactly with lambda expressions? Is this a bug in Spring that is fixable or does Java 8 just not provide the necessary information?
I'm using Spring version 4.1.0.RELEASE and Java 8 update 20.