Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic interface for enums in Java

I have a web-application on Hibernate / Spring and I have few enums that I want to use in applications

public enum MerchantStatus {
    NEW("New"),
    ...

    private final String status;

    MerchantStatus(String status) {
        this.status = status;
    }

    public static MerchantStatus fromString(String status) {..}    

    public String toString() {..}
}

And

public enum EmployerType {
    COOL("Cool"),
    ...

    private final String type;

    EmployerType (String type) {
        this.type = type;
    }

    public static EmployerType fromString(String type) {..}    

    public String toString() {..}
}

I want to create converter to convert my enum objects to string and and vice versa. It is something like this:

public class MerchantStatusConverter implements AttributeConverter<MerchantStatus, String> {
    public String convertToDatabaseColumn(MerchantStatus value) {..}

    public MerchantStatus convertToEntityAttribute(String value) {..}
}

The problem is that I don't want to create converter for each enum and ideally it should be generic class/interface and I will use polymorphism here. The problem is that fromString is static method and it seems that it is impossible to create static method that returns generic type.

Are there any solutions of this problem?

like image 712
Boris Parnikel Avatar asked Jul 16 '17 14:07

Boris Parnikel


2 Answers

The problem is that I don't want to create converter for each enum and ideally it should be generic class/interface and I will use polymorphism here.

You have no choice as your AttributeConverter implementation could not be parameterized when you annotate your entity.

You should indeed specify it only with the AttributeConverter class :

@Enumerated(EnumType.STRING)
@Convert(converter = MerchantStatusConverter.class)
private MerchantStatus merchantStatus;

But you could define an abstract class that defines the logic and subclassing it in each enum class.
To achieve it, you should introduce an interface in front of each enum class that declares a fromString() and a toString() method.

The interface :

public interface MyEnum<T extends MyEnum<T>>{

     T fromString(String type);
     String toString(T enumValue);
}

The enum that implements the interface :

public enum MerchantStatus implements MyEnum<MerchantStatus> {

    NEW("New"), ...


    @Override
    public MerchantStatus fromString(String type) {
     ...
    }

    @Override
    public String toString(MerchantStatus enumValue) {
     ...
    }
}

The abstract AttributeConverter class :

public abstract class AbstractAttributeConverter<E extends MyEnum<E>> implements AttributeConverter<E, String> {

    protected MyEnum<E> myEnum;

    @Override
    public String convertToDatabaseColumn(E attribute) {
        return myEnum.toString(attribute);
    }

    @Override
    public E convertToEntityAttribute(String dbData) {
        return myEnum.fromString(dbData);
    }
}

And concrete AttributeConverter class that needs to declare a public constructor to assign the protected myEnum field to an enum value (whatever of it):

public class MerchantStatusAttributeConverter extends AbstractAttributeConverter<MerchantStatus> {
   public MerchantStatusAttributeConverter(){
      myEnum = MerchantStatus.NEW; 
   }
}
like image 74
davidxxx Avatar answered Oct 09 '22 02:10

davidxxx


If you want a general Converter for all your enum classes, you can use reflection, as long as you stick to a naming convention.

Your convention seem to be that you use toString() for enum -> String conversion, and a static fromString(String) for String -> enum conversion.

A Converter for that would be something like this:

public class EnumConverter<T extends Enum<T>> implements AttributeConverter<T, String> {
    private final Method fromStringMethod;

    public EnumConverter(Class<T> enumClass) {
        try {
            this.fromStringMethod = enumClass.getDeclaredMethod("fromString", String.class);
        } catch (NoSuchMethodException e) {
            throw new NoSuchMethodError(e.getMessage());
        }
        if (! Modifier.isStatic(this.fromStringMethod.getModifiers()))
            throw new NoSuchMethodError("fromString(String) is not static");
        if (this.fromStringMethod.getReturnType() != enumClass)
            throw new NoSuchMethodError("fromString(String) does not return " + enumClass.getName());
    }

    public String convertToDatabaseColumn(T value) {
        return value.toString();
    }

    @SuppressWarnings("unchecked")
    public T convertToEntityAttribute(String value) {
        try {
            return (T) this.fromStringMethod.invoke(null, value);
        } catch (IllegalAccessException e) {
            throw new IllegalAccessError(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Error calling fromString(String): " + e, e);
        }
    }
}

You then construct it by naming the class, e.g.

new EnumConverter<>(MerchantStatus.class)
new EnumConverter<>(EmployerType.class)
like image 43
Andreas Avatar answered Oct 09 '22 02:10

Andreas