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

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2009 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.core.convert.support;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.util.Assert;
/**
* Converts from a String to a java.lang.Enum by calling {@link Enum#valueOf(Class, String)}.
@@ -29,7 +30,13 @@ import org.springframework.core.convert.converter.ConverterFactory;
final class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToEnum(targetType);
Class<?> enumType = targetType;
while(enumType != null && !enumType.isEnum()) {
enumType = enumType.getSuperclass();
}
Assert.notNull(enumType, "The target type " + targetType.getName()
+ " does not refer to an enum");
return new StringToEnum(enumType);
}
private class StringToEnum<T extends Enum> implements Converter<String, T> {