How to get valueOf & values of an Enum and call methods on an interface it implements when defined as a generic class param

三世轮回 提交于 2020-04-30 07:14:13

问题


I want to convert Strings to Enums 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!