[Apex] Apex reports an error System.StringException: Invalid id: Solution / Determine the search field is not empty

Apex reports an error System.StringException: Invalid id: Solution / Determine the search field is not empty

Happening scene

An error is reported when checking whether a search field of a custom object is empty. Example of error code:

List<Custom__c> recordList = [SELECT Id, Name, Lookup__c FROM Custom__c WHERE Id in :idList];
for (Integer i = 0; i < recordList.size(); i++) {
    
    
	if (recordList[i].Lookup__c == null || recordList[i].Lookup__c == '') {
    
    
        // do something
    }
}

The above code will report an error:System.StringException: Invalid id:

cause

Although in Apex, Id is a type inherited from String, it ''still reports an error if the search field is directly compared with it. The strange thing is that if the above code is changed, recordList[0].Lookup__c == null || recordList[0].Lookup__c == ''it will not report an error. I didn't go into the reason for this. In short, the performance was very strange.

Solution

If we want to determine whether the field is empty look, in fact, you do not need ''to judge, just to determine that it is not nullon it. The judgment conditions in the above code can be changed to the following two:

  • if (recordList[i].Lookup__c == null) {
          
          }
    
  • if (String.isBlank(recordList[i].Lookup__c)) {
          
          }
    

The first is recommended, with the following isBlankmethod than the above is determined directly integrally nullabout twice as slow.

Guess you like

Origin blog.csdn.net/qq_35714301/article/details/114268209