4
System.Type siteType = Type.forName('Site');
Site newSite = (Site) siteType.newInstance();

This fails with the error: System.TypeException: Invalid conversion from runtime type System.Site to Site

Reflection works in most cases for creating a new instance of an SObject, but in cases where there is also a system class with the same name we get that instead of the SObject. Is it possible to create a new instance of a Site SObject via reflection?

6

There's actually two Site objects, one in System and one in Schema. The former has a bunch of static methods like changePassword and createExternalUser, while the latter represents the sObject Site you're looking for. To get at that one, use its full name:

Type sitesObjectType = Type.forName('Schema.Site');
Site siteRecord = (Site)sitesObjectType.newInstance();
  • Perfect. In retrospect I should have been able to guess the namespace. – SSS Dec 15 '18 at 12:37

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.