OOPortal OOPortal


IDL Constructed Types   «Prev  Next»
Lesson 8 Mapping for unions
Objective Describe and use the Java produced by the Mapping for IDL Unions.

Java produced by the Mapping for IDL Unions

An IDL union X is mapped to a final Java class named X, which has a default constructor, a discriminator accessor (the discriminator is what indicates which possible case the union currently represents), and accessors and mutators for the union branches and default. As always, a helper class and a holder class are also generated.

Example

Let us try another Weather Service example, introducing a union into the IDL. Here is the IDL and the Java class it produces:


Union example Weather Service

Using unions in Java

When using a Java class for a union, you set the value of objects by instantiating them using the no-args constructor and then calling the desired mutator method, which not only sets the value, but also sets the discriminator. To access the union object, you must check the discriminator in order to find out which accessor can be called. Note from the example code above that calling an inappropriate accessor results in an exception being thrown.
Continuing with our example, here is some sample client code to demonstrate how to use generated union classes in your own Java code:

package Module4Java;
import Module4.*;
public class UnionClient{
 public static void main(String args[]){
  //Initialize ORB ..
  WeatherService wService = null;
  //Obtain reference to remote WeatherService..
  ForecastDetail nyDetails = wService.
   getForecastDetail("New York");
  ForecastType detailsType = nyDetails.discriminator();
  if(detailsType == ForecastType.cold){
   System.out.println("New York is cold with a wind 
     chill of "+nyDetails.windchill());
  }
  // ...
 }
}

You have now learned how IDL unions map to Java and how to use the Java code generated for unions in your own Java clients or servers. In the next lesson, you will learn the Java mapping for IDL arrays and how to use the resulting Java.

IDL To JavaMapping for Unions - Quiz

Click on the Quiz link below to test your knowledge of IDL-to-Java mapping for unions.
IDL To JavaMapping for Unions - Quiz