instanceof Keyword in Salesforce Apex

instanceof Keyword in Salesforce Apex

Using Salesforce Apex, if you want to verify at run time or dynamically whether an object is actually an instance of a particular class, then we can make use of the instanceof keyword. 

The instanceof keyword in Salesforce Apex 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.

Sample Code:

List < sObject > listRecords = new List < sObject >();
Account objAccount = [
    SELECT Name, Id
    FROM Account
    LIMIT 1
];
listRecords.add( 
    objAccount 
);
Contact objContact = [
    SELECT Name, Id
    FROM Contact
    LIMIT 1
];
listRecords.add( 
    objContact 
);
for ( sObject objRecord : listRecords ) {
    
    if ( objRecord instanceof Account ) {
        
        System.debug(
            'Object Type is ' +
            objRecord.getSObjectType()
        );
        System.debug(
            'Account Instance'
        );
        
    } else {
        
        System.debug(
            'Object Type is ' +
            objRecord.getSObjectType()
        );
        System.debug(
            'Non-Account Instance'
        );
        
    }
    
}

Leave a Reply