简体   繁体   English

我们可以在 Salesforce(apex) 中动态转换 SObject 吗?

[英]Can we Cast SObject dynamically in Salesforce(apex)?

Is it possible to Cast SObject dynamically?是否可以动态转换 SObject?

Example :例子 :

I know we can do this :我知道我们可以这样做:

(Account) Sobject

But I want to do this as the return type of sObject changes based on certain parameters.但我想这样做,因为 sObject 的返回类型会根据某些参数发生变化。

(Dynamically Passing the Name) SObject

Any Kind of way around will be helpful... Thanks in advance :)任何方式都会有所帮助......提前致谢:)

Unfortunately, no.抱歉不行。 I ran into this recently while writing a TestFactory class.我最近在编写 TestFactory 类时遇到了这个问题。 The best I could do was cast the responses back into the expected type in the code that was calling the TestFactory's methods.我能做的最好的事情就是将响应转换回调用 TestFactory 方法的代码中的预期类型。

Yes, you can do it.是的,你可以做到。 For example -例如 -

Class ABC {

   public static List<Object> method1(String sObjectType){
      List<Object> records = new List<Object>();
      if(sObjectType == 'Account'){
          records = [SELECT Id, Name FROM Account];
      } else if(sObjectType == 'Account'){
          records = [SELECT Id, Name FROM Contact];
      }
      return records;
   }

}

You can check the sObject Type of List -您可以检查列表的 sObject 类型 -

if(records instanceof List<Account>){
  // your code here
} else if(records instanceof List<Contact>){
  // your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM