Search code examples
javaenumstype-safety

Java - How can I use Type Safe Enumerations as switch-case statement?


I am developing a Java program, where I have to use the following TypeSafeEnum (that is given in an external component):

public class MyInterfaceTypeEnum
    extends TypeSafeEnum
{
    public MyInterfaceTypeEnum(String paramString, int paramInt)
    {
        super(paramString, paramInt);
    }

    public static final MyInterfaceTypeEnum UNKNOWN = new MyInterfaceTypeEnum("UNKNOWN", 0);
    public static final MyInterfaceTypeEnum TCP = new MyInterfaceTypeEnum("TCP", 10);
    public static final MyInterfaceTypeEnum UDP = new MyInterfaceTypeEnum("UDP", 20);
    public static final MyInterfaceTypeEnum IPX = new MyInterfaceTypeEnum("IPX", 30);
    public static final MyInterfaceTypeEnum RS232 = new MyInterfaceTypeEnum("RS232", 40);
}

My task-process class has the following method:

private void processInterface(MyInterfaceTypeEnum type)
{
    switch(type)
    {
    case RS232:
        {
            // do action
            break;
        }
    case TCP:
    case UDP:
        {
            // do action
            break;
        }
    case IPX:
        {
            // do action
            break;
        }
    case UNKNOWN:
    default:
        {
            // do default action
            break;
        }
    }
}

The compiler fails on the switch statement's line with the following message:

Cannot switch on a value of type MyInterfaceTypeEnum. Only convertible int values, strings or enum variables are permitted.

I googled, but everywhere was written: this TypeSafeEnum pattern may okay. Please give me ideas how to work around this.

UPDATED:

Important to mention: the implementation of MyInterfaceTypeEnum can't be changed by me (it is part of a used (imported) component). Therefore I am forced to use it. So, basic situation is: the "enum" (misused class) is already given.

If I would give up using MyInterfaceTypeEnum, I also would not be able to use a lot of functions (those using this type-safe-enum intensively). So I have no other choice but to accept this and try to find the simpliest possibility.

I know, if-else statement-tree can be used. But I want to avoid that. Since the MyInterfaceTypeEnum was added in an external component (implemented by others and I can't change it).


Solution

  • Provided you have a field name or a field value in TypeSafeEnum with public access getter, which do store the values of the constructor TypeSafeEnum (String paramString, int paramInt), you could:

    private void processInterface(MyInterfaceTypeEnum type){
    switch(type.getName()) {
    case "RS232":
        {
            // do action
            break;
        }
    case "TCP":
    

    or do similar with the getter for value (which would be less readable.). @GhostCat's approach of wrapping your class into a real enum looks better to me.