Newer Version Available
Using the instanceof Keyword
If you need to verify at run time whether an object is actually an instance of a particular class, use the instanceof keyword. The instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable alternative for the declared type of the expression on the left.
1if (Reports.get(0) instanceof CustomReport) {
2 // Can safely cast it back to a custom report object
3 CustomReport c = (CustomReport) Reports.get(0);
4 } else {
5 // Do something with the non-custom-report.
6}Implementation Considerations
Keep these considerations in mind while using the instanceof keyword.
- If the declared type on the left of the expression using the instanceof keyword is always an instance of
the target type, compilation fails. An example expression that’s always true and
therefore causes a compilation
error.
1Account acc = new Account(); 2if(acc instanceOf Account) { 3 //condition is always true since an instance of Account is always an instance of Account 4} - When you perform instanceof checks, implicit type casting from String to ID can result in unexpected behavior if the String meets the requirements to be cast to an ID.
Versioned Behavior Changes
In API version 60.0 and later, if a List data type implements the Iterable data type, compilation fails. An example instanceof expression that causes a compilation error.
1public class BaseClass {}
2public class SubClass extends BaseClass {}
3
4List<SubClass> subClasses = new List<SubClass>();
5if(subClasses instanceof Iterable<BaseClass>) {
6 //condition is always true since an instance of SubClass is always an instance of BaseClass
7}In API version 32.0 and later, instanceof returns false if the left operand is a null object. In API version 31.0 and earlier, instanceof returns true in this case. For example, the code sample returns false in API version 32.0 and later.
1Object o = null;
2Boolean result = o instanceof Account;
3System.assertEquals(false, result);