汎用オブジェクト(SObject)で参照先のオブジェクトを取得する方法

イシュー

  • クラスのデータ型が分からない場合でも動作するようにSObjectをつかってデータ操作する場合は、.(ドット)を使ったメソッドは使えない。
  • 代わりに getメソッドを使う

    SObject standardObj = [SELECT Id, Name, Account__c, Account__r.AccountType__c, EstimateDate__c FROM Opportunity__c WHERE Id = :sc.getRecord().Id];
    System.debug('Account__c=' + standardObj.get('Account__c'));
    
  • 参照型のオブジェクトの場合は、getSObjectメソッドを使う

    System.debug('Account__r.AccountType__c=' + standardObj.getSObject('Account__r').get('AccountType__c'));
    

参考

拡張クラスのクラス名の取得

  • クラス名を取得する

    public ProductController(ApexPages.StandardController controller) {
      sc = controller;
      System.debug('getApiRef=' + sc.getRecord().getSObjectType().getDescribe().getName());
    }
    

参考