How do I introspect the class of a variable in APEX?
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;
Someone asked me this earlier today. Here is a more dynamic solution.
MyClass mine = new MyClass();
String myStr = String.valueOf(mine);
String className = myStr.split(':')[0];
System.assertEquals('MyClass', className);
A generic code of Salesforce Apex to explain :
public class Animal {}
public class Bird extends Animal {}
Animal a = new Bird(); // Success
System.debug(a); // Bird:[]
System.debug((Bird)a); // Bird:[]
System.debug((Animal)a); // Bird:[]
System.debug(a instanceof Bird); // true
System.debug((Animal)a instanceof Bird); // true
System.debug((Bird)a instanceof Bird); // Operation instanceof is always true since an instance of Bird is always an instance of Bird
System.debug((Bird)a instanceof Animal); // Operation instanceof is always true since an instance of Bird is always an instance of Animal