How do I introspect the class of a variable in APEX?

barelyknown picture barelyknown · Mar 3, 2012 · Viewed 9.1k times · Source

I would like to know the class of a variable/property at runtime. For example:

Integer i = 5;

//pseudo-code
if (i.className == 'Integer') {
    System.debug('This is an integer.');
} else {
    System.debug('This is not an integer, but a ' + i.className);
}

I can't find the method/property that returns the class type in the documentation (assuming it's there). Am I missing it?

Answer

Adam picture Adam · Mar 4, 2012

From p. 122 of the Apex Developer Guide:

If you need to verify at runtime whether an object is actually an instance of a particular class, use the instanceof keyword...

But, you cannot use the instanceof keyword on an instance of the the class of its subclasses or else you'll receive a compile error. For example:

Integer i = 0;
System.debug(i instanceof Integer);

>> COMPILE ERROR: Operation instanceof is always true since an instance of Integer is always an instance of Integer.

You need to use the instanceof keyword on superclasses only. For example:

System.debug((Object)i instanceof Integer);

>> true

If you ever need information on type of the Class itself, check the System.Type methods (pg 396 of current Apex developer's guide. Here's are some examples:

Type integerType;
integerType = Type.forName('Integer');
integerType = Integer.class;