问题
I want to convert String
s to Enum
s for a set of enum types. I use an interface to mark what set of enums to convert and define a couple of methods used during conversion:
public interface SymbolEnum {
String getCode();
String getDescription();
}
Here's an example of one of the Enum
types that I want to derive from a String
:
@RequiredArgsConstructor // using lombok
public enum Element implements SymbolEnum {
IRON("FE", "iron"),
HYDROGEN("H", "hydrogen"),
@Getter
private final String code;
@Getter
private final String description;
}
If the String matches the enum constant name, the enum code property, or the enum description property then I want to convert to that enum. Otherwise, the code should thrown an IllegalArgumentException
.
I'm using Spring's Converter
interface to implement my converter. Converter
is parameterized as Converter<S,T>
. What should I use for T
? I know that T
should extend Enum
and implement SymbolEnum
. Here's what I tried:
public class StringToSymbolEnum<T extends Enum<?> & SymbolEnum> implements Converter<String, T> {
@Override
public T convert(String source) {
try {
return T.valueOf(source); // compile error
} catch (IllegalArgumentException notEnumConstant) {
for (Enum enum : T.values()) { // compile error
if (T.getDescription().equalsIgnoreCase(source) // compile error
|| T.getCode().equalsIgnoreCase(source)) { // compile error
return T;
}
}
throw notEnumConstant;
}
}
}
回答1:
You would need to pass a description of the enum to the StringToSymbolEnum
constructors. Perhaps either the Class<T>
(for use in Enum.valueOf
) or T[]
from values
.
Note, T
should be defined:
T extends Enum<T> & SymbolEnum
Instead of using a wildcard.
来源:https://stackoverflow.com/questions/59779592/how-to-get-valueof-values-of-an-enum-and-call-methods-on-an-interface-it-imple