Working with variants


This document was published with and applies to ArcGIS 9.3.
A 10 version also exists.

In this topic


About working with variants

The variant data type can contain a wide arrary of subtypes. With variants, all types can be contained in a single type variant. Everything in the Java programming language is an object. Even primitive data types can be encapsulated inside objects if required. Every class in Java extends java.lang.Object. Consequently, methods in ArcObjects that take variants as parameters can be passed any object code in the ArcGIS application programming interface (API) for Java.

Calling methods with variant objects as parameters

For methods that take variants as parameters, any object types can be passed, as all objects derive from java.lang.Object. As this is considered a widening cast, an explicit cast to Object is not needed. If you want to pass primitives as parameters to methods, when variants are required, the corresponding primitive wrapper class can be used.
 
There are also times when methods need to take null value parameters in place of variants. For example, IRowBuffer.setValue may need to set a null value to a column in a record. In this case, the following will not work and throws an exception.
 
See the following code example:
 

[Java]
row.setValue(indexField, null);
Instead of passing a null directly, pass in com.esri.arcgis.interop.NullVariant.TYPE. See the following code example:
 

[Java]
row.setValue(indexField, com.esri.arcgis.interop.NullVariant.TYPE);

Using methods that return variants

When using variant objects returned by methods, explicitly downcast those objects to the corresponding wrapper object. For example, if expecting a String, downcast to java.lang.String; if expecting a Short, downcast to Short's wrapper class, that is, java.lang.Short. See the following code example:
 

[Java]
ICursor spCursor = spTable.ITable_search(spQueryFilter, false);
/*Iterate over the rows.*/
IRow spRow = spCursor.nextRow();
while (spRow != null)
{
    Short ID = (Short)(spRow.getValue(1));
    String name = (String)(spRow.getValue(2));
    Short baseID = (Short)(spRow.getValue(3));
    System.out.println("ID=" + ID + "\t name=" + name + "\tbaseID=" + baseID);
    /* Move to the next row.*/
    spRow = spCursor.nextRow();
}

IRowBuffer is a superinterface of IRow and defines the getValue(int)method as:
    public Object getValue(int index)throws IOException, AutomationException 

The value of the field with the specified index. Parameters: index - The index
    (in)Returns: return value. A Variant
The return value is an Object, specified by the Javadoc as a variant. Therefore, the value can be downcasted to String or Short, depending on their type in the queried geodatabase.