StringToEnumConverterFactory class from enum value

Update StringToEnumConverterFactory to search superclasses until
Class.isEnum() returns true. This allows conversion when the
enum class is obtained from the enum value:

    public static enum SubFoo {
        BAR { String s() { return "x"; } };
        abstract String s();
    }

    conversionService.convert("BAR", SubFoo.BAR.getClass())

This fix is particularly important when converting collections of
enums.

Issue: SPR-10329
This commit is contained in:
Phillip Webb
2013-02-25 13:17:40 -08:00
parent e2e4cbe6b3
commit 9a6c6b9ee6
2 changed files with 33 additions and 2 deletions

View File

@@ -17,6 +17,7 @@
package org.springframework.core.convert.support;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -212,6 +213,11 @@ public class DefaultConversionTests {
assertEquals(Foo.BAR, conversionService.convert("BAR", Foo.class));
}
@Test
public void testStringToEnumWithSubclss() throws Exception {
assertEquals(SubFoo.BAZ, conversionService.convert("BAZ", SubFoo.BAR.getClass()));
}
@Test
public void testStringToEnumEmptyString() {
assertEquals(null, conversionService.convert("", Foo.class));
@@ -226,6 +232,24 @@ public class DefaultConversionTests {
BAR, BAZ;
}
public static enum SubFoo {
BAR {
@Override
String s() {
return "x";
}
},
BAZ {
@Override
String s() {
return "y";
}
};
abstract String s();
}
@Test
public void testStringToLocale() {
assertEquals(Locale.ENGLISH, conversionService.convert("en", Locale.class));