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());
}
// ...
}
}
Corba Programming C++
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