Describe and use the Java produced by the Mapping for IDL enums.
Java produced by the Mapping for IDL enums
The following section describes how to use the Java produced by the mapping for IDL enums, which is a type that can take one of a given set of values
using the IDL of Corba.
Java enum mapping
An IDL enum is a type that can take one of a given set of values. Java mapping makes the possible values accessible as both objects and as ints mapped to the index of the value in the set. This mapping covers both possible ways in which people have typically represented enumerated types in Java. An IDL enum X is mapped to a Java class also called X. This Java class has a final static int field and a final static X field for every label in the enum. It has a constructor (nonpublic) that takes an int index and creates the corresponding X object (using the constructor). This class also has an instance method value() to get the index int for an X object and a static from -int() method to covert from an int to the corresponding object. In addition to the enum class, helper and holder classes, XHelper and XHolder, are also generated.
Example
Let's look at an example in the following enum-example that defines and uses an enum in IDL and the resulting Java. ForecastType is mapped to ForecastType.java as well as corresponding ForecastTypeHelper.java and ForecastTypeHolder.java files.
Enums Forecast Type Weather
Using enum classes
An important aspect of the enum mapping is that it guarantees that there is only one instance of a given enum object. All the enum objects are the static final members of the class, they are singletons.
This means that equality tests will work correctly for enums, and it is such equality testing that lies at the heart of most enum usage. Let us look at a sample client fragment for the above:
//Initialize ORB ..
WeatherService wService = null;
//Obtain reference to remote WeatherService..
ForecastType nyForecast = wService.getForecast
("New York");
if(nyForecast == ForecastType.hot)
{
System.out.println("The big apple is in the oven.");
}
// ...
As you can see in the usage of ForecastType.hot, the enum objects can be used simply by referring to the static fields of the enum class.
In the next lesson, we will recap the module thus far and focus on writing Java code based on IDL using sequences, structs, and enums.