HOWTO Use Generated Enums in Java Switch Statements
When using enums in your definition of your data types, you should take into account that the Java generated code does not use the native implementation of Enum. Take as an example the following data type defined in IDL.
enum PrimitiveEnum { ENUM1, ENUM2, ENUM3 }; struct msg { PrimitiveEnum testEnum; };
As you can see in the following code snipped, the generated Enum class extends com.rti.dds.util.Enum rather than the native java.lang.Enum.
import com.rti.dds.util.Enum; import com.rti.dds.cdr.CdrHelper; import java.util.Arrays; import java.io.ObjectStreamException; public classPrimitiveEnumextendsEnum { public static final PrimitiveEnum ENUM1 = new PrimitiveEnum("ENUM1",0); public static final int _ENUM1 = 0; public static final PrimitiveEnum ENUM2 = new PrimitiveEnum("ENUM2",1); public static final int _ENUM2 = 1; public static final PrimitiveEnum ENUM3 = new PrimitiveEnum("ENUM3",2); public static final int _ENUM3 = 2; ...
One of the consequences of this is that you cannot use the generated enumerators directly in switch statements. The following code snippet shows how to implement a switch statement using the generated class.
PrimitiveEnum primitiveEnum = PrimitiveEnum.ENUM1; switch (primitiveEnum.value()){ case PrimitiveEnum._ENUM1: System.out.println("ENUM1"); break; case PrimitiveEnum._ENUM2: System.out.println("ENUM2"); break; case PrimitiveEnum._ENUM3: System.out.println("ENUM3"); break; }
Comments
rehan81
Thu, 02/20/2020 - 01:03
Permalink
helpful
I was facing some issue but this guide helped me.