Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 485
barelyknown Avatar asked Mar 03 '12 16:03

barelyknown


3 Answers

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;
like image 160
Adam Avatar answered Sep 28 '22 06:09

Adam


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);
like image 37
Phil R Avatar answered Sep 28 '22 06:09

Phil R


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
like image 44
Cray Kao Avatar answered Sep 28 '22 06:09

Cray Kao